# OpenCV Contour, bounding box, minimum rectangle, minimum closed circle detection

Source: Internet
Author: User
```Import CV2 Import NumPy as NP # function Cv2.pyrdown () is to reduce the image resolution to the original half img = Cv2.pyrdown (Cv2.imread ("g:/python_code/opencvstudy/ Images/timg.jpg ", Cv2. imread_unchanged) # Convert the image to grayscale, then binary ret, Thresh = Cv2.threshold (Cv2.cvtcolor (Img.copy (), Cv2. Color_bgr2gray), 127, 255, Cv2. thresh_binary) image, contours, hier = cv2.findcontours (Thresh, Cv2. Retr_external, Cv2. Chain_approx_simple) for C in contours: # bounding box: # Find bounding box coordinates # boundingrect () Convert profile to (x,y,w,h A simple border, cv2.rectangle () draws a rectangle [green (0, 255, 0)] x, Y, W, h = cv2.boundingrect (c) Cv2.rectangle (IMG, (x, y), (x + W, y + h), (0, 255, 0), 2) # Minimum rectangular area: # 1 calculates the minimum rectangular area 2 calculates the rectangle Vertex 3 for this is calculated as a floating-point number, and the pixel is an integer, so convert 4 to draw the contour [red (0, 0, 255)] # F IND Minimum Area rect = Cv2.minarearect (c) # Calculate coordinates of the minimum area rectangle box = Cv2.box Points (Rect) # Normalize coordinates to integers box = np.int0 (box) # Draw Contours Cv2.drawcontours (IMG, [Box], 0, (0, 0, 255), 3) # mostSmall closed Circle Contour: # Calculate Center and radius of minimum enclosing circle[blue (255, 0, 0)] (x, y), radius = cv2.minenclosing Circle (c) # cast to integers center = (int (x), int (y)) radius = int (RADIUS) # draw the circle IMG = CV 2.circle (IMG, center, RADIUS, (255, 0, 0), 2) # Contour detection: Draw Contour cv2.drawcontours (img, contours, 1, (255, 0, 0), 1) cv2.imshow (
"Contours", img) Cv2.waitkey () cv2.destroyallwindows ()```

Related Keywords:

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.