Discuz! Board

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 520|回复: 0

OpenCV 实现滑块缺口位置计算

[复制链接]

19

主题

11

回帖

255

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
255
发表于 2024-5-10 16:19:11 | 显示全部楼层 |阅读模式
  1. import io
  2. import cv2
  3. import numpy as np
  4. from PIL import Image


  5. class DetectDistanceXY:

  6.     def detectDistanceX(self, imgSlider, imgBackground):
  7.         """X坐标缺口检测"""

  8.         # imgSlider = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgSlider))), cv2.COLOR_BGR2GRAY)
  9.         # imgBackground = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgBackground))), cv2.COLOR_BGR2GRAY)

  10.         imgSliderGray = cv2.cvtColor(np.array(Image.open(imgSlider)), cv2.COLOR_BGR2GRAY)
  11.         imgBackgroundGray = cv2.cvtColor(np.array(Image.open(imgBackground)), cv2.COLOR_BGR2GRAY)
  12.         # 寻找最佳匹配
  13.         res = cv2.matchTemplate(self._tran_canny(imgSliderGray), self._tran_canny(imgBackgroundGray), cv2.TM_CCOEFF_NORMED)
  14.         # 最小值,最大值,并得到最小值, 最大值的索引
  15.         min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

  16.         return max_loc[0]

  17.     def detectDistanceY(self, imgSlider, imgBackground):
  18.         #  传入二进制图片
  19.         # target_gray = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgSlider))), cv2.COLOR_BGR2GRAY)
  20.         # template_gray = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgBackground))), cv2.COLOR_BGR2GRAY)
  21.         # 根据路径读取图片
  22.         imgSliderGray = cv2.cvtColor(np.array(Image.open(imgSlider)), cv2.COLOR_BGR2GRAY)
  23.         imgBackgroundGray = cv2.cvtColor(np.array(Image.open(imgBackground)), cv2.COLOR_BGR2GRAY)
  24.         res = cv2.matchTemplate(imgSliderGray, imgBackgroundGray, cv2.TM_CCOEFF_NORMED)
  25.         min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
  26.         return max_loc[0]

  27.     def _tran_canny(self, image):
  28.         """消除噪声"""

  29.         image = cv2.GaussianBlur(image, (3, 3), 0)
  30.         return cv2.Canny(image, 100, 200)


  31. if __name__ == '__main__':
  32.     detectdistancexy = DetectDistanceXY()

  33.     targetFile = r'target.png'
  34.     templateFile = r'template.png'
  35.     print(detectdistancexy.detectDistanceX(targetFile, templateFile))
  36.     print(detectdistancexy.detectDistanceY(targetFile, templateFile))
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2024-10-7 01:31 , Processed in 0.033436 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表