PYTHON__OPENCV detection Image Object Contour __python

Source: Internet
Author: User
Tags abs
step1: Load the picture and turn it into a grayscale image
Image = Cv2.imread ("353.jpg")
Gray = Cv2.cvtcolor (image, Cv2. Color_bgr2gray)
Step2: Using the Sobel operator to compute the gradient in the x,y direction, and then subtracting the gradient in the y direction in the x direction, by this subtraction we leave an image region with a high gradient and a low vertical gradient.
GRADX = Cv2. Sobel (Gray, ddepth=cv2.cv.cv_32f, Dx=1, dy=0, ksize=-1)
GradY = Cv2. Sobel (Gray, ddepth=cv2.cv.cv_32f, dx=0, Dy=1, Ksize=-1) # Subtract the y-gradient from the x-gradient
gradient = C V2.subtract (GRADX, GradY)
gradient = cv2.convertscaleabs (gradient)

After performing this step, the resulting image is as follows:

Step3: Removes noise from the image. First, the low pass filter is used to smooth the image (9 x 9 kernel), which will help to smooth the high-frequency noise in the image. The goal of Low-pass filter is to reduce the rate of image change. Replace each pixel with the average value of the pixels around the pixel. This will smooth and replace areas where the intensity changes significantly.

Then, the binary value of fuzzy image is evaluated. Any pixel that is not greater than 90 in the gradient image is set to 0 (black). Otherwise, the pixel is set to 255 (white).

# blur and threshold the image
blurred = Cv2.blur (gradient, (9, 9))
(_, Thresh) = Cv2.threshold (blurred, 90, 255, Cv2. Thresh_binary)

After performing this step, the resulting image is as follows:
Step4: In the picture above we see a lot of black bees in the body area, we need to fill the space with white, so that the next program easier to identify insect areas, which requires some morphological aspects of the operation.

Kernel = cv2.getstructuringelement (cv2. Morph_rect, (a))
closed = Cv2.morphologyex (Thresh, Cv2. Morph_close, Kernel)

The image after processing is as follows:
Step5: From the above we found that there are some small white spots on the image, which will interfere with the detection of the insect contour, to remove them. 4 morphological corrosion and dilation were performed respectively.

# Perform a series of erosions and dilations
closed = Cv2.erode (closed, None, iterations=4)
closed = Cv2.dilate (cl osed, None, iterations=4)

After you perform this step, you get the following figure:
step6: Find the outline of the insect area. The first parameter of the Cv2.findcontours () function is the picture to retrieve. Must be a two-value graph, that is, black and white (not grayscale), so read the image to first convert to grayscale, and then into a two-value graph, we in the third step with the Cv2.threshold () function has been two value graph. The second parameter represents the search pattern for the contour, with four kinds: cv2. Retr_external indicates that only the outer contour Cv2 is detected. The contour of the retr_list detection does not establish a hierarchical relationship cv2. The Retr_ccomp establishes two levels of contours, the upper layer of which is an outer boundary, and the inside layer is the boundary information of the inner hole. If there is another connected object in the inner hole, the boundary of the object is also at the top level. Cv2. Retr_tree establishes the outline of a hierarchy tree structure.

The third parameter is the approximate method of the contour Cv2. The Chain_approx_none stores all the contour points, and the pixel positions of the adjacent two points are less than 1, i.e. Max (ABS (X1-X2), ABS (Y2-Y1)) ==1

Cv2. Chain_approx_simple compress horizontal, vertical, and diagonal elements, leaving only the end coordinates of that direction, such as a rectangular contour with only 4 points to hold the profile information

The Cv2.findcontours () function returns two values, one for the contour itself and one for each profile. The Cv2.findcontours () function returns the first value where each element in the list,list is an outline in the image, expressed in Ndarray in NumPy. The coordinates of each point on the contour are preserved in each ndarray. We sort the list, and the most point is the contour of the insect we're looking for.
The contour is drawn on the image by Cv2.drawcontours in the OpenCV. The first argument is to indicate on which image the outline is drawn, and the second parameter is the contour itself, in Python is a list the third parameter specifies which contour in the outline list to draw, and if it is-1, draw all of its outlines the fourth parameter is the color of the outline line fifth parameter is the thickness of the outline line
Cv2.minarearect () function:
The rectangle that contains the minimum area of the point set is mainly obtained, which can have deflection angle, and can not be parallel to the boundary of the image.

(CNTs, _) = Cv2.findcontours (Closed.copy (), Cv2. Retr_external, Cv2. chain_approx_simple)
C = sorted (CNTs, Key=cv2.contourarea, Reverse=true) [0]

# Compute the rotated bounding box of the largest contour
rect = Cv2.minarearect (c)
box = np.int0 (cv2.cv.BoxPoints (rect))

# Draw a bounding box a Rounded the detected barcode and display the image
cv2.drawcontours (image, [box],-1, (0, 255, 0), 3)
cv2.imshow (" Image ", image"
cv2.imwrite ("contoursimage2.jpg", image)
Cv2.waitkey (0)

This step is followed by the following graphic:
step7: cropping. The box holds the coordinates of the four vertices of the green rectangular area. I will crop the insect image as shown in the red rectangle below. Finds the maximum minimum value of the x,y coordinates of the four vertices. New images of high =maxy-miny, wide =maxx-minx.

Xs = [I[0] for I in box]
Ys = [i[1] for I in box]
x1 = min (xs)
x2 = max (xs)
y1 = min (Ys)
y2 = max (Ys)
hight = y2-y1
width = x2-x1
cropimg = image[y1:y1+hight, X1:x1+width]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.