滑块图像距离计算

本文出自: https://www.cnblogs.com/jackzhuo/p/18662516 ,并非原创,如需要转载请移步自原文并注明出处

"""
 滑块图像距离计算
"""
import random
 
import cv2
import numpy as np
import requests
import ddddocr
 
def distance_cv(slice_url,bg_url):
    """
    :param slice_url: 滑块(缺口)图片地址
    :param bg_url: 背景图地址
    :return: distance
    :rtype:integer
    """
    slice_image = np.asarray(bytearray(requests.get(slice_url).content),dtype=np.uint8)
    slice_image = cv2.imdecode(slice_image,1)
    slice_image = cv2.Canny(slice_image,255,255)
 
    bg_image = np.asarray(bytearray(requests.get(bg_url).content), dtype=np.uint8)
    bg_image = cv2.imdecode(bg_image, 1)
    bg_image = cv2.pyrMeanShiftFiltering(bg_image,5,50)
    bg_image = cv2.Canny(bg_image, 255, 255)
 
    result = cv2.matchTemplate(bg_image,slice_image,cv2.TM_CCOEFF_NORMED)
 
    min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(result)
    return max_loc[0]
 
def distance_orc(bg_url,slice_url):
    slide = ddddocr.DdddOcr(det=False,ocr=False,show_ad=False)
    slide_image = requests.get(slice_url).content
    bg_image =  requests.get(bg_url).content
    result = slide.slide_match(slide_image, bg_image, simple_target=True)
    # 返回距离
    return result['target'][0]
 
def distance_puzzle(bg_img_path,puzzle_img_path):
    """
    根据背景图和缺口图,计算滑块距离
    :param bg_img_path:
    :param puzzle_img_path:
    :return:
    """
    img = cv2.imdecode(np.fromfile(bg_img_path,dtype=np.uint8),cv2.IMREAD_COLOR)
    tpl = cv2.imdecode(np.fromfile(puzzle_img_path,dtype=np.uint8),cv2.IMREAD_COLOR)
 
    img_gry = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    _,img_bw = cv2.threshold(img_gry,127,255,cv2.THRESH_BINARY)
 
    tpl = cv2.cvtColor(tpl,cv2.COLOR_BGR2GRAY)
    for row in range(tpl.shape[0]):
        for col in range(tpl.shape[1]):
            if tpl[row,col] == 0:
                tpl[row,col] = 96
    lower = np.array([96])
    upper = np.array([96])
    mask = cv2.inRange(tpl,lower,upper)
    tpl[mask == 0] = 0
    tpl[mask != 0] =255
 
    result =cv2.matchTemplate(img_bw,tpl,cv2.TM_CCOEFF_NORMED)
    _,_,_,max_loc = cv2.minMaxLoc(result)
    distance = int(max_loc[0] * 0.5833333333333333) + random.randint(0,2)
    return distance
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容