思路:
将虚线膨胀为实线,通过高度和宽度找到轮廓,再将轮廓内的面积涂白色
img = cv2.imread(imagePath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray_test = gray.copy()
binary_test = cv2.adaptiveThreshold(clean_gray(gray_test),
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 15, -5)
diate = cv2.dilate(binary_test, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 20)))#虚线膨胀成为直线
cv_show(diate)
canny = cv2.Canny(diate, 200, 255)
# iterations=5 两个数字也能连在一起,paddle两个数字很容易识别
_, total_contours, HIERARCHY = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = [cnt for cnt in total_contours if
max( cv2.minAreaRect(cnt)[1][0],cv2.minAreaRect(cnt)[1][1]) > 1000
and min( cv2.minAreaRect(cnt)[1][0],cv2.minAreaRect(cnt)[1][1]) < 40
] # 虚线的长度
if len(contours)!=1:
print('%s contours异常第 %s 矩形'%(self.file,i))
cv2.drawContours(gray, contours, -1, (255, 255), -1)