1. 程式人生 > 其它 >驗證碼之滑塊驗證碼

驗證碼之滑塊驗證碼

class SlideCrack(object):
    def __init__(self, gap, bg):
        """
        init code
        :param gap: 缺口圖片
        :param bg: 背景圖片
        :param out: 輸出圖片
        """
        self.front = gap
        self.bg = bg

    @staticmethod
    def clear_white(img):
        # 清除圖片的空白區域,這裡主要清除滑塊的空白
        img_data = base64.b64decode(img)
        img_array 
= np.fromstring(img_data, np.uint8) img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR) rows, cols, channel = img.shape min_x = 255 min_y = 255 max_x = 0 max_y = 0 for x in range(1, rows): for y in range(1, cols): t = set(img[x, y])
if len(t) >= 2: if x <= min_x: min_x = x elif x >= max_x: max_x = x if y <= min_y: min_y = y elif y >= max_y: max_y
= y img1 = img[min_x:max_x, min_y: max_y] return img1 def template_match(self, tpl, target): th, tw = tpl.shape[:2] result = cv2.matchTemplate(target, tpl, cv2.TM_CCOEFF_NORMED) # 尋找矩陣(一維陣列當作向量,用Mat定義) 中最小值和最大值的位置 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) tl = max_loc br = (tl[0] + tw, tl[1] + th) # 繪製矩形邊框,將匹配區域標註出來 # target:目標影象 # tl:矩形定點 # br:矩形的寬高 # (0,0,255):矩形邊框顏色 # 1:矩形邊框大小 cv2.rectangle(target, tl, br, (0, 0, 255), 2) return tl @staticmethod def image_edge_detection(img): edges = cv2.Canny(img, 100, 200) return edges def discern(self): img1 = self.clear_white(self.front) img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY) slide = self.image_edge_detection(img1) img_data = base64.b64decode(self.bg) img_array = np.fromstring(img_data, np.uint8) back = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR) back = self.image_edge_detection(back) slide_pic = cv2.cvtColor(slide, cv2.COLOR_GRAY2RGB) back_pic = cv2.cvtColor(back, cv2.COLOR_GRAY2RGB) pos = self.template_match(slide_pic, back_pic) # 輸出橫座標, 即 滑塊在圖片上的位置 return pos