| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 
 | """1.读取图像
 2.灰度化
 3.二值化,查找到合适阈值
 4.在二值化上查找轮廓(只检测外层轮廓)
 5.构建和二值化shape一样的纯黑色图像(值为0)
 6.将度盘区域轮廓,使用实心化填充,画在mask上,白色
 7.二值化图像,与实心化填充的结果 做减法,找到瑕疵区域
 8.对瑕疵区域做闭运算(先膨胀,后腐蚀)
 9.找到瑕疵区域的轮廓
 10.计算瑕疵区域的面积,判断是否属于瑕疵(大于10为瑕疵)
 11.如果为瑕疵,拟合瑕疵区域的最小外接圆
 12.将最小外接圆画在原始图像上
 """
 import cv2
 import numpy as np
 import math
 
 
 im_cpu = cv2.imread("../data/cv_cpu.png")
 
 im_gray = cv2.cvtColor(im_cpu, cv2.COLOR_BGR2GRAY)
 
 ret, im_bin = cv2.threshold(im_gray, 162, 255, cv2.THRESH_BINARY)
 
 
 
 
 contours, hierarchy = cv2.findContours(im_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
 
 mask = np.zeros(im_bin.shape, np.uint8)
 
 mask = cv2.drawContours(mask, contours, -1, (255, 0, 0), -1)
 
 
 im_sub = cv2.subtract(mask, im_bin)
 
 
 k = np.ones((10, 10), np.uint8)
 im_close = cv2.morphologyEx(im_sub, cv2.MORPH_CLOSE, k, iterations=3)
 
 
 contours, hierarchy = cv2.findContours(im_close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
 
 
 (x, y), radius = cv2.minEnclosingCircle(contours[1])
 center = (int(x), int(y))
 radius = int(radius)
 area = math.pi * radius * radius
 print("area:", area)
 if area > 12:
 print("度盘表面有缺陷")
 
 print("center:", center, " radius:", radius)
 cv2.circle(im_close, center, radius, (255, 0, 0), 2)
 cv2.imshow("im_gaussian_blur2", im_close)
 
 cv2.circle(im_cpu, center, radius, (0, 0, 255), 2)
 cv2.imshow("im_cpu2", im_cpu)
 else:
 print("无瑕疵")
 
 while True:
 key = cv2.waitKey()
 if key == 27:
 cv2.destroyAllWindows()
 break
 
 |