python 滑块验证码破解之获取缺口位置
Python环境搭建OpenCV
适用于windows
pip install --upgrade setuptools
pip install numpy Matplotlib
pip install opencv-python
注意图片路径指定好,路径不要有中文,最好用/,别用\ 。cv2读不到图片不会报路径错误,先去看路径问题。
#取的验证码图片(大小图)
import cv2
import numpy as np
from PIL import Image as Im
otemp = './xt.png' #原图缺口小图
oblk = './dt.png' #原图缺口大图
target = cv2.imread(otemp, 0)
template = cv2.imread(oblk, 0)
w, h = target.shape[::-1]
temp = './temp.jpg' #临时储存 每次识别覆盖就好了
targ = './targ.jpg' #临时储存 每次识别覆盖就好了
cv2.imwrite(temp, template)
cv2.imwrite(targ, target)
target = cv2.imread(targ)
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
target = abs(255 - target)
cv2.imwrite(targ, target)
target = cv2.imread(targ)
template = cv2.imread(temp)
result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)
x, y = np.unravel_index(result.argmax(), result.shape)
#缺口位置
print((y, x, w, h))
# 测试 在指定位置画上矩形框
image_path = r'./result.png' #保存测试结果图
image = cv2.imread(otemp)
first_point = (y,x) #定位好的坐标
last_point = (w,h) #定位好的坐标
cv2.rectangle(image, first_point, last_point, (0, 255, 0), 2)
cv2.imwrite(image_path, image)
最新代码:
import cv2
# 显示或保存图片
def cv_show(name, img, save=False):
if save:
cv2.imwrite(name, img)
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 获取滑块的大小
def fix_img(filename):
# 1.为了更高的准确率,使用二值图像
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 2.将轮廓提取出来
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
# 3.用绿色(0, 255, 0)来画出最小的矩形框架
x, y, w, h = cv2.boundingRect(cnt)
rect_x = x + w
rect_y = y + h
# print(x, y, rect_x, rect_y) # x,y是矩阵左上点的坐标,w,h是矩阵的宽和高
img = cv2.rectangle(img, (x, y), (rect_x, rect_y), (0, 255, 0), 1)
cv_show('img.png', img, True) # 用绿色线框画出滑块的大小
# 高度和宽度
mixintu = img[y:rect_y, x:rect_x]
cv_show("mixintu.png", mixintu, True) # 裁剪出滑块的区域
return mixintu
def mian():
# 1.对滑块进行图片处理
tp_img = fix_img('./fadebg.png') # 裁掉透明部分,找出滑块的大小
tp_edge = cv2.Canny(tp_img, 100, 200)
tp_pic = cv2.cvtColor(tp_edge, cv2.COLOR_GRAY2BGR)
cv_show("1.png", tp_edge, True)
# 2.对背景进行图片处理
bg_img = cv2.imread('fullbg.png')
bg_edge = cv2.Canny(bg_img, 100, 200)
bg_pic = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2BGR)
cv_show("2.png", bg_pic, True)
# 3.模板匹配matchTemplate
res = cv2.matchTemplate(bg_pic, tp_pic, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# print(min_val, max_val, min_loc, max_loc) # 最小值,最大值,最小值的位置,最大值的位置
# 绘制方框【方便查看】
X = max_loc[0]
th, tw = tp_pic.shape[:2]
t1 = max_loc # 左上角点的位置
br = (t1[0] + tw, t1[1] + th) # 右下角点的坐标
cv2.rectangle(bg_img, t1, br, (0, 0, 225), 2) # 绘制矩形
cv_show('out.png', bg_img, True)
if __name__ == '__main__':
mian()
最新代码转载自:https://blog.csdn.net/mixintu/article/details/109702875