| 10 | |
| 11 | |
| 12 | class SlideCrack(object): |
| 13 | def __init__(self, gap_img, bg): |
| 14 | self.gap_img = gap_img |
| 15 | self.bg = bg |
| 16 | |
| 17 | @staticmethod |
| 18 | def pixel_is_equal(image1, image2, x, y): |
| 19 | """ |
| 20 | 判断两张图片的像素是否相等,不想等即为缺口位置 |
| 21 | :param image1: |
| 22 | :param image2: |
| 23 | :param x: x坐标 |
| 24 | :param y: y 坐标 |
| 25 | :return: |
| 26 | """ |
| 27 | # 取两个图片的像素点 |
| 28 | pixel1 = image1.load()[x, y] |
| 29 | pixel2 = image2.load()[x, y] |
| 30 | threshold = 60 # 像素色差 |
| 31 | if abs(pixel1[0]-pixel2[0]) < threshold and abs(pixel1[1]-pixel2[1]) < threshold and abs(pixel1[2]-pixel2[2]) <threshold: |
| 32 | return True |
| 33 | else: |
| 34 | return False |
| 35 | |
| 36 | def get_gap(self, image1, image2): |
| 37 | """ |
| 38 | 获取缺口位置 |
| 39 | :param image1:完整图片 |
| 40 | :param image2: 带缺口的图片 |
| 41 | :return: |
| 42 | """ |
| 43 | left = 50 # 设置一个起始量,因为验证码一般不可能在左边,加快识别速度 |
| 44 | for i in range(left, image1.size[0]): |
| 45 | for j in range(image1.size[1]): |
| 46 | if not self.pixel_is_equal(image1, image2, i, j): |
| 47 | left = i |
| 48 | return left |
| 49 | return left |
| 50 | |
| 51 | def run(self): |
| 52 | image1 = Image.open(self.bg) |
| 53 | image2 = Image.open(self.gap_img) |
| 54 | # 获取缺口的位置 |
| 55 | gap = self.get_gap(image1, image2) |
| 56 | return gap |