写一份和下面代码意义相同的代码import cv2 import numpy as np img1=cv2imreadimagesmubanpng img2=cv2cvtColorimq1cv2COLOR BGR2GRAY retimg3=cv2thresholdimg2120255cv2THRESH BINARY INV #img4=cv2adaptiveThresholdimg2255cv2A
import cv2 import numpy as np
读入图像
img1 = cv2.imread('images/muban.png')
转换为灰度图像
img2 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
二值化处理
ret,img3 = cv2.threshold(img2,120,255,cv2.THRESH_BINARY_INV)
形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) img4 = cv2.morphologyEx(img3,cv2.MORPH_OPEN,kernel) img5 = cv2.morphologyEx(img4,cv2.MORPH_OPEN,kernel)
查找轮廓
coutours,h = cv2.findContours(img5,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
绘制轮廓
cv2.drawContours(img1,coutours,0,(0,0,255),2) cv2.drawContours(img1,coutours,1,(0,0,255),2)
计算轮廓面积并判断是否有瑕疵
area = cv2.contourArea(coutours[0]) + cv2.contourArea(coutours[1]) if area > 200: print("这个零件有瑕疵,具体看红圈的部分") else: print("这个零件无瑕疵,可以通过质检")
显示图像
cv2.imshow('muban',img5) cv2.imshow('gray',img1) cv2.waitKey(0
原文地址: https://www.cveoy.top/t/topic/ePaP 著作权归作者所有。请勿转载和采集!