diff --git a/check_template.py b/check_template.py new file mode 100644 index 0000000..30a022a --- /dev/null +++ b/check_template.py @@ -0,0 +1,35 @@ +import cv2 +import numpy as np +import matplotlib.pyplot as plt +img = cv2.imread("./images/good.jpg") +#plt.imshow(img) +#plt.show() + +#图像二值化 +gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) +ret,binary = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) +binary = cv2.bitwise_not(binary) +#获取指定形状的内核,第一个参数:内核的形状,内核的大小,锚点的位置(-1,-1)锚点位于中心单 +se = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3),(-1,-1)) +binary = cv2.morphologyEx(binary,cv2.MORPH_OPEN,se) +#plt.imshow(binary,cmap='gray') +#plt.show() + +#图像轮廓提取 +contours,hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) +height,width = img.shape[:2] +template=[] +for c in range (len(contours)): + x,y,w,h = cv2.boundingRect(contours[c]) + area = cv2.contourArea(contours[c]) + if h<(height/2): + continue + if area<10: + continue + print(x,y,w,h) + img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),10,80,0) + ret = cv2.drawContours(img,contours,c,(0,255,0),10,8) + template = binary[y:y+h,x:x+w] +cv2.imwrite("./images/good_template.png", template) +plt.imshow(template,cmap="gray") +plt.show() \ No newline at end of file