OpenCV will often measured object area, perimeter, centroid, bounding box, etc.
Seeking graphic geometric moments, and determining the center of the minimum enclosing rectangle python achieved
import cv2 import numpy as np __author__ = "boboa" def measure_demo(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) print("threshold value", ret) cv2.imshow("binary", thresh) outImage,contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for i, contour inthe enumerate (Contours): # traversing the entire contour Area = cv2.contourArea (Contour) # cv2.boundingRect returns four parameters (x, Y) coordinates of the upper left corner of the rectangle, (w, h) is the width and height of a rectangular x, Y, W, H = cv2.boundingRect (Contour) # circumscribed rectangle size Rate = min (W, H) / max (W, H) # aspect ratio # image is calculated in the central moments mm = cv2.moments (Contour) CX = mm [ " MlO " ] / mm [ " M00 " ] CY = mm [ " M01 " ] / mm [ " M00 " ] #The geometry of the center position, mm is the dictionary type cv2.circle (Image, (np.int (CX), np.int (CY)), 2, (0, 255, 255), -1 ) cv2.rectangle (Image , (X, Y), (X + W, Y + H), (0, 0, 255), 2) # circumscribed rectangle Print ( " Contour Area " , Area) cv2.imshow ( " its measure Contours " , Image) IF the __name__ == " __main__ " : IMG = cv2.imread ( " Image / 123.jpg " ) cv2.namedWindow ( " INPUT Image " , cv2.WINDOW_AUTOSIZE) cv2.imshow ("input image", img) measure_demo(img) cv2.waitKey(0) cv2.destroyAllWindows()
operation result
Fitting polygon (application: the geometry is selected in the picture) Python implemented
"" " ApproxPolyDP (Curve, Epsilon, Closed [, approxCurve]) -> approxCurve curve- fitting curve epsilon- curve fitting article number (int) closed- fit curve is closed (True or False) polygonal fitting
" " " approxCurve = cv2.approxPolyDP (contour, 10 , True) Print (approxCurve.shape) # contoured to fit the number of polygons> into red pattern profile 6 IF approxCurve.shape [0]> 6 : cv2.drawContours (DST, contours , I, (0,0, 255), 2 ) # contouring fit polygonal contour pattern number = 3 for blue elif approxCurve.shape [0] == 3 : cv2.drawContours (DST, contours, I, ( 255 , 0, 0), 2 ) #Remaining number of polygon contouring fit figure outline yellow the else : cv2.drawContours (DST, Contours, I, (0, 255,255), 2)