前言
滑塊拼圖驗證碼的失敗難度在於每次圖片上缺口位置不一樣,需識別圖片上拼圖的缺口位置,使用python的OpenCV庫來識別到
環境准備
pip 安裝 opencv-python
pip installl opencv-python
OpenCV(Open Source Computer Vision Library)是一個開源的計算機視覺庫,提供了很多處理圖片、視頻的方法。
OpenCV庫提供了一個方法(matchTemplate()):從一張較大的圖片中搜索一張較小圖片,計算出這張大圖上各個區域和小圖相似度。
調用這個方法后返回一個二維數組(numpy庫中ndarray對象),從中就能拿到最佳匹配區域的坐標。
這種使用場景就是滑塊驗證碼上背景圖片是大圖,滑塊是小圖。
准備2張圖片
場景示例
先摳出2張圖片,分別為background.png 和 target.png
計算缺口位置
import cv2
# 作者-上海悠悠 QQ交流群:730246532
# blog地址 https://www.cnblogs.com/yoyoketang/
def show(name):
'''展示圈出來的位置'''
cv2.imshow('Show', name)
cv2.waitKey(0)
cv2.destroyAllWindows()
def _tran_canny(image):
"""消除噪聲"""
image = cv2.GaussianBlur(image, (3, 3), 0)
return cv2.Canny(image, 50, 150)
def detect_displacement(img_slider_path, image_background_path):
"""detect displacement"""
# # 參數0是灰度模式
image = cv2.imread(img_slider_path, 0)
template = cv2.imread(image_background_path, 0)
# 尋找最佳匹配
res = cv2.matchTemplate(_tran_canny(image), _tran_canny(template), cv2.TM_CCOEFF_NORMED)
# 最小值,最大值,並得到最小值, 最大值的索引
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc[0] # 橫坐標
# 展示圈出來的區域
x, y = max_loc # 獲取x,y位置坐標
w, h = image.shape[::-1] # 寬高
cv2.rectangle(template, (x, y), (x + w, y + h), (7, 249, 151), 2)
show(template)
return top_left
if __name__ == '__main__':
top_left = detect_displacement("target.png", "background.png")
print(top_left)
運行效果看到黑色圈出來的地方就說明找到了缺口位置
調試完成后去掉 show 的這部分代碼
# 展示圈出來的區域
# x, y = max_loc # 獲取x,y位置坐標
# w, h = image.shape[::-1] # 寬高
# cv2.rectangle(template, (x, y), (x + w, y + h), (7, 249, 151), 2)
# show(template)
缺口的位置只需得到橫坐標,距離左側的位置top_left為184
參考博客:
https://zhuanlan.zhihu.com/p/65309386
https://blog.csdn.net/weixin_42081389/article/details/87935735
https://blog.csdn.net/qq_30815237/article/details/86812716