Python 滑块验证

一、安装python opencv模块

pip install opencv-python

二、准备好图片

准备好带缺口的图片和缺口图片

template.png:
template.png
target.png:
在这里插入图片描述

三、代码:

def caculate_distance():
    otemp = 'F:\\test\\target.png'
    oblk = 'F:\\test\\template.png'
    # otemp,oblk = oblk,otemp # 这两个路径要是不清楚的话 可以替换一下再尝试
    target = cv2.imread(otemp, 0)
    template = cv2.imread(oblk, 0)
    
    # 缩小
    # target = cv2.resize(target,None,fx=0.6,fy=0.6,interpolation=cv2.INTER_CUBIC)
    # template = cv2.resize(template,None,fx=0.6,fy=0.6,interpolation=cv2.INTER_CUBIC)

    w, h = target.shape[::-1]
    print('w is {},h is {}'.format(w,h))
    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)
    # 展示圈出来的区域
    cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)
    show(template)
    print('x is {},y is {}'.format(x, y))
    return x, y

def show(name):
    cv2.imshow('Show', name)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

四、结果:

在这里插入图片描述

注意:opencv存在中文路径的问题,在读取写入中文路径的图片时,请使用一下方式:

		target = self.cv_imread(template_path)
        targ = os.path.join(temp_res_dir,'targ.jpg')
        cv2.imencode('.jpg', target)[1].tofile(targ)

	def cv_imread(self,file_path):
        cv_img=cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),cv2.IMREAD_COLOR)
        ## imdecode读取的是rgb,如果后续需要opencv处理的话,需要转换成bgr,转换后图片颜色会变化
        ##cv_img=cv2.cvtColor(cv_img,cv2.COLOR_RGB2BGR)
        return cv_img

具体代码需要根据上面的代码稍微改一下,主要就是 imdecode 和 imencode这俩函数

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值