用openCV和python写一个物体缺陷检测的代码
时间: 2023-02-19 21:09:29 浏览: 145
可以参考下面的代码:
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对图像进行高斯模糊
blur = cv2.GaussianBlur(gray, (5,5), 0)
# 进行Canny边缘检测
canny = cv2.Canny(blur, 50, 150)
# 进行膨胀和腐蚀,以便更容易识别边缘
dilate = cv2.dilate(canny, None, iterations=1)
erode = cv2.erode(dilate, None, iterations=1)
# 寻找轮廓
contours, hierarchy = cv2.findContours(erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 遍历轮廓并绘制
for cnt in contours:
area = cv2.contourArea(cnt)
# 如果面积超过阈值,则认为是物体缺陷
if area > 200:
cv2.drawContours(img, [cnt], 0, (0,255,0), 2)
cv2.putText(img, "Defect", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
# 显示结果
cv2.imshow("Result", img)
cv2.waitKey(0)
阅读全文