缺陷检测程序

2023-10-05  本文已影响0人  大龙10

书名:计算机视觉40例从入门到深度学习:OpenCV-Python
作者:李立宗
出版社:电子工业出版社
出版时间:2022-07-01
ISBN:9787121436857


二、理论基础

3、最小包围圆形

4、筛选标准

三、缺陷检测步骤

缺陷检测程序的完整流程图如图所示。


缺陷检测程序的完整流程图

四、缺陷检测程序

运行结果
import numpy as np
import cv2
# ====step1 读取图像=====
img = cv2.imread('d:\\pill.jpg')
cv2.imshow("pill",img)

# ====step2 预处理=====
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 

ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)) #核
opening1 = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 1)

# ====step3 完成距离的计算,确定前景=====
dist_transform = cv2.distanceTransform(opening1,cv2.DIST_L2,3)
ret, fore = cv2.threshold(dist_transform,0.3*dist_transform.max(),255,0) 

# ====step4  去噪处理====
kernel = np.ones((3,3),np.uint8)
opening2 = cv2.morphologyEx(fore,cv2.MORPH_OPEN,kernel)

# ====step5 提取轮廓 ====
opening2 =np.array(opening2,np.uint8)
contours,hirearchy=cv2.findContours(opening2,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

# ====step6 缺陷检测 ====
count = 0
font = cv2.FONT_HERSHEY_COMPLEX
for cnt in contours:
    (x,y),radius= cv2.minEnclosingCircle(cnt)
    center=(int(x),int(y))
    radius=int(radius)
    circle_img=cv2.circle(opening2,center,radius,(255,255,255),1)
    area=cv2.contourArea(cnt)
    area_circle=3.14*radius*radius
    if area/area_circle>=0.5:
        img=cv2.putText(img,'OK',center,font,1,(255,255,255),2)
    else:
        img=cv2.putText(img,'BAD',center,font,1,(255,255,255),2)
    count+=1

img=cv2.putText(img,'sum='+str(count),(20,30),font,1,(255,0,255),2)

# ====step5 显示处理结果 ====
cv2.imshow("result",img)

cv2.waitKey()
cv2.destroyAllWindows()
上一篇 下一篇

猜你喜欢

热点阅读