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)
原文地址:https://www.cnblogs.com/qianxia/p/11103831.html
时间: 2024-10-01 04:46:32