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 ()