- 寻找工件轮廓,并计算其面积
- 寻找工件的最小外接矩形,并计算其面积
- 计算轮廓面积和矩形面积之差。
工件如下图所示:
import imutils
import cv2
import numpy as np
image = cv2.imread("111.bmp")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# 遍历轮廓集
for c in cnts:
M = cv2.moments(c)
area = cv2.contourArea(c)
if area <1000000:
continue
# 在图像上绘制轮廓
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
print("area:",area)
# 寻找轮廓的最小外接矩形
# x, y, w, h = cv2.boundingRect(c)
# cv2.rectangle(image,(x, y), (x + w, y + h), (0, 0, 255), 2)
# 获取最小外接矩阵,中心点坐标,宽高,旋转角度
rect = cv2.minAreaRect(c)
# 获取矩形四个顶点,浮点型
box = cv2.boxPoints(rect)
box = np.int0(box)
print(box)
left_point_x = np.min(box[:, 0])
right_point_x = np.max(box[:, 0])
top_point_y = np.max(box[:, 1])
bottom_point_y = np.min(box[:, 1])
left_point_y = sorted(box[:, 1][np.where(box[:, 0] == left_point_x)])[-1]
right_point_y = sorted(box[:, 1][np.where(box[:, 0] == right_point_x)])[0]
top_point_x = sorted(box[:, 0][np.where(box[:, 1] == top_point_y)])[-1]
bottom_point_x = sorted(box[:, 0][np.where(box[:, 1] == bottom_point_y)])[0]
vertices = [[left_point_x, left_point_y],[bottom_point_x, bottom_point_y],
[right_point_x, right_point_y], [top_point_x, top_point_y]]
print(vertices)
cv2.circle(image, (left_point_x, left_point_y), 20, (255, 255, 255), -1)
cv2.circle(image, (bottom_point_x, bottom_point_y), 20, (255, 0, 0), -1)
cv2.circle(image, (top_point_x, top_point_y), 20, (0, 255, 0), -1)
cv2.circle(image, (right_point_x, right_point_y), 20, (0, 0, 255), -1)
# 计算矩形的最长边和最短边
long_size = np.sqrt(np.math.pow((left_point_x-bottom_point_x),2) + np.math.pow((left_point_y-bottom_point_y),2))
short_size = np.sqrt(np.math.pow((left_point_x-top_point_x),2) + np.math.pow((left_point_y-top_point_y),2))
print("矩形的面积:",long_size*short_size)
print("轮廓的面积:",area)
poor_area = (long_size * short_size - area)/area
print("缺陷面积占轮廓面积的比例:",poor_area*100,"%")



