OpenCV中經常會測量對象的面積,周長,質心,邊界框等
求圖形幾何矩中心 並求最小外接矩形python實現
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 in enumerate(contours): # 遍歷全部輪廓 area = cv2.contourArea(contour) # cv2.boundingRect返回四個參數(x,y)為矩形左上角的坐標,(w,h)是矩形的寬和高 x, y, w, h = cv2.boundingRect(contour) # 外接矩形大小 rate = min(w, h) / max(w, h) # 寬高比 # 計算圖像中的中心矩 mm = cv2.moments(contour) cx = mm["m10"]/mm["m00"] cy = mm["m01"]/mm["m00"] # 幾何圖形的中心位置 , mm是字典類型 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) # 外接矩形 print("contour area ", area) cv2.imshow("measure contours", image) if __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()
運行結果
多邊形擬合(應用:選擇圖片中幾何體形狀)python實現
""" approxPolyDP(curve, epsilon, closed[, approxCurve]) -> approxCurve curve-擬合曲線 epsilon-擬合曲線條數(int) closed-擬合曲線是否閉合(True or False) 多邊形擬合
""" approxCurve = cv2.approxPolyDP(contour,10,True) print(approxCurve.shape) #畫輪廓多邊形擬合數目>6的圖形輪廓為紅 if approxCurve.shape[0] > 6: cv2.drawContours(dst,contours,i,(0,0,255),2) # 畫輪廓多邊形擬合數目=3的圖形輪廓為藍 elif approxCurve.shape[0] == 3: cv2.drawContours(dst,contours,i,(255,0,0),2) # 畫其余數目的輪廓多邊形擬合的圖形輪廓為黃 else: cv2.drawContours(dst,contours,i,(0,255,255),2)