破解滑动验证码(二)识别验证码缺口

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值