class TemplateMatching():
def read_fg_img(self):
fg_img = cv2.imread('./fg.png') #numpy array
fg_gray = cv2.cvtColor(fg_img,cv2.COLOR_BGR2GRAY)
return fg_gray
def read_bg_img(self):
bg_img = cv2.imread('./bg.png')
bg_gray = cv2.cvtColor(bg_img,cv2.COLOR_BGR2GRAY)
return bg_gray
def crop_fg_img(self,gray_img):
'''
通过角点检测得到的坐标,裁剪出匹配模板
'''
gray_nparray = np.float32(gray_img)
dst = cv2.cornerHarris(gray_nparray,2,3,0.22)
dst = cv2.dilate(dst,None)
shape = dst.shape
threshold = 0.01*dst.max()
#角点坐标
coordinate_lst = []
for j in range(shape[0]):
for i in range(shape[1]):
if dst[j][i] > threshold:
coordinate_lst.append(j)
y_index_lst = [] #fg_img中横坐标是确定的,只需要确定在y方向上的位置
for i in range(len(coordinate_lst)-1):
if (coordinate_lst[i+1] - coordinate_lst[i]) > 6:
y_index_lst.append(coordinate_lst[i])
y_index_lst.append(coordinate_lst[i+1])
# print(y_index_lst[-1])
return gray_img[y_index_lst[0]-16:y_index_lst[-1]+16,2:57], (y_index_lst[0]-18,y_index_lst[-1]+18)
def match(self,template,bg_gray):
'''
相关系数匹配
'''
res = cv2.matchTemplate(bg_gray, template, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
left_top = max_loc # 左上角
right_bottom = (left_top[0] + 53, left_top[1] + 55) # 右下角
#show
# cv2.rectangle(bg_gray, left_top, right_bottom, 255, 2) # 画出矩形位置
# cv2.imshow('bg_img',bg_gray)
# cv2.waitKey(0)
return int((left_top[0] + right_bottom[0])/2)
def bg_img_crop(self,bg_gray,y_index):
'''
滑块只在一定的高度上,所以裁剪出背景图片对应高度的部分用来匹配,提高准确度
'''
bg_gray_crop = bg_gray[y_index[0] : y_index[1] , :]
return bg_gray_crop
def entrance(self):
'''
return:验证码的缺口的横坐标位置,由于这个位置是相对于图片左端的,
所以在拖动的时候还需要减去偏置(从滑块中心位置开始拖动,减去滑块宽度的1/2)来补偿
'''
bg_gray = self.read_bg_img()
fg_gray = self.read_fg_img()
template_data = self.crop_fg_img(fg_gray)
template = template_data[0]
y_index = template_data[1]
print('y:',y_index)
bg_gray_crop = self.bg_img_crop(bg_gray,y_index)
location = self.match(template,bg_gray_crop)
return location
破解滑动验证码(二)识别验证码缺口
最新推荐文章于 2024-06-13 19:48:36 发布