|
- import io
- import cv2
- import numpy as np
- from PIL import Image
- class DetectDistanceXY:
- def detectDistanceX(self, imgSlider, imgBackground):
- """X坐标缺口检测"""
- # imgSlider = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgSlider))), cv2.COLOR_BGR2GRAY)
- # imgBackground = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgBackground))), cv2.COLOR_BGR2GRAY)
- imgSliderGray = cv2.cvtColor(np.array(Image.open(imgSlider)), cv2.COLOR_BGR2GRAY)
- imgBackgroundGray = cv2.cvtColor(np.array(Image.open(imgBackground)), cv2.COLOR_BGR2GRAY)
- # 寻找最佳匹配
- res = cv2.matchTemplate(self._tran_canny(imgSliderGray), self._tran_canny(imgBackgroundGray), cv2.TM_CCOEFF_NORMED)
- # 最小值,最大值,并得到最小值, 最大值的索引
- min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
- return max_loc[0]
- def detectDistanceY(self, imgSlider, imgBackground):
- # 传入二进制图片
- # target_gray = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgSlider))), cv2.COLOR_BGR2GRAY)
- # template_gray = cv2.cvtColor(np.array(Image.open(io.BytesIO(imgBackground))), cv2.COLOR_BGR2GRAY)
- # 根据路径读取图片
- imgSliderGray = cv2.cvtColor(np.array(Image.open(imgSlider)), cv2.COLOR_BGR2GRAY)
- imgBackgroundGray = cv2.cvtColor(np.array(Image.open(imgBackground)), cv2.COLOR_BGR2GRAY)
- res = cv2.matchTemplate(imgSliderGray, imgBackgroundGray, cv2.TM_CCOEFF_NORMED)
- min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
- return max_loc[0]
- def _tran_canny(self, image):
- """消除噪声"""
- image = cv2.GaussianBlur(image, (3, 3), 0)
- return cv2.Canny(image, 100, 200)
- if __name__ == '__main__':
- detectdistancexy = DetectDistanceXY()
- targetFile = r'target.png'
- templateFile = r'template.png'
- print(detectdistancexy.detectDistanceX(targetFile, templateFile))
- print(detectdistancexy.detectDistanceY(targetFile, templateFile))
复制代码
|
|