对缺口滑块轨迹计算代码的封装
建议先阅读:爬虫: 滑块验证码破解
# -*- coding: utf-8 -*-
# Author: 桑葚ICE
# Email: 152516cc@gmail.com
# Blog: iicey.github.io
# JueJin: juejin.im/user/5c64dce8e51d45013c40742c
import os
import sys
import cv2
import requests
class CalcSlideDistance:
@staticmethod
def find_pic(target, template):
target_rgb = cv2.imread(target)
target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
template_rgb = cv2.imread(template, 0)
res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
value = cv2.minMaxLoc(res)
return value[2:][0][0], value[2:][1][0]
@staticmethod
def generate_tracks(distance):
distance += 20
v = 0
t = 0.2
forward_tracks = []
current = 0
mid = distance * 3 / 5 # 减速阀值
while current < distance:
if current < mid:
a = 2 # 加速度为+2
else:
a = -3 # 加速度-3
s = v * t + 0.5 * a * (t ** 2)
v = v + a * t
current += s
forward_tracks.append(round(s))
back_tracks = [-3, -3, -2, -2, -2, -2, -2, -1, -1, -1]
return forward_tracks, back_tracks
def calc_result(self, username, target_url, template_url):
template_path = os.path.join(os.getcwd(), 'img', f'slide_1_{username}.png')
target_path = os.path.join(os.getcwd(), 'img', f'slide_2_{username}.png')
# 对滑块图片发请求保持为背景图片
target = requests.get(url=target_url).content
with open(target_path, 'wb') as f_tar:
f_tar.write(target)
template = requests.get(url=template_url).content
with open(template_path, 'wb') as f_tem:
f_tem.write(template)
value_1, value_2 = self.find_pic(target_path, template_path) # 计算缺口距离
forward_tracks, back_tracks = self.generate_tracks(value_2) # 加速轨迹, 减速轨迹
os.remove(target_path), os.remove(template_path) # 删除滑块图片
return forward_tracks, back_tracks
if __name__ == '__main__':
calc_slide_distance = CalcSlideDistance()
calc_slide_distance.calc_result("定义滑块图片名", "大图的url", "小图的url")