用Python编写一下提取工件缺陷几何特征代码包含面积,周长,质心,并把缺陷画出来
时间: 2023-06-09 19:04:57 浏览: 48
你好,这是一个比较复杂的问题,需要一定的图像处理和计算几何知识。下面是一个简单的参考实现:
``` python
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 读取图像并转为灰度图
img = cv2.imread('defect_img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 图像二值化
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 形态学操作,去除噪点和小的空洞
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# 轮廓检测
contours, hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 遍历每个缺陷并提取几何特征
for i, cnt in enumerate(contours):
area = cv2.contourArea(cnt) # 面积
perimeter = cv2.arcLength(cnt,True) # 周长
M = cv2.moments(cnt) # 中心矩
if M['m00'] == 0:
cx = cy = 0
else:
cx, cy = int(M['m10']/M['m00']), int(M['m01']/M['m00']) # 质心
# 显示缺陷轮廓和特征信息
cv2.drawContours(img, [cnt], -1, (0, 0, 255), 2)
cv2.putText(img, 'Defect #%