import cv2 import numpy as np # The function cv2.pyrDown() is to reduce the image resolution to half of the original img = cv2.pyrDown(cv2.imread("G:/Python_code/OpenCVStudy/images/timg.jpg", cv2.IMREAD_UNCHANGED)) # Convert the image to grayscale and then binarize 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() converts the outline into a simple border of (x, y, w, h), 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 Calculate the minimum rectangular area 2 Calculate the rectangle vertex 3 Since the calculation is a floating point number, and the pixel is an integer, so convert it 4 Draw the outline [red (0, 0, 255)] # find minimum area rect = cv2.minAreaRect(c) # calculate coordinates of the minimum area rectangle box = cv2.boxPoints(rect) # normalize coordinates to integers box = np.int0(box) # draw contours cv2.drawContours(img, [box], 0, (0, 0, 255), 3) # Outline of the smallest closed circle: # calculate center and radius of minimum enclosing circle[蓝色(255, 0, 0)] (x, y), radius = cv2.minEnclosingCircle(c) # cast to integers center = (int(x), int(y)) radius = int(radius) # draw the circle img = cv2.circle(img, center, radius, (255, 0, 0), 2) # Contour detection: draw contours cv2.drawContours(img, contours, -1, (255, 0, 0), 1) cv2.imshow("contours", img) cv2.waitKey() cv2.destroyAllWindows()
OpenCV contour, bounding box, minimum rectangle, minimum closed circle detection
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324686576&siteId=291194637
Recommended
Ranking