赞
踩
带缺口的图片长这样:
缺口图片:
识别过程:
- # -*- coding: utf-8 -*-
-
- import cv2
- from matplotlib import pyplot as plt
-
- # 带有缺口的图片
- path1 = r"jietu_1.png"
- # 模板图片
- path2 = r"jietu_2.png"
-
-
- def pic2gray(pic_path, new_path=''):
- # 转灰度图
- pic_path_rgb = cv2.imread(pic_path)
- pic_path_gray = cv2.cvtColor(pic_path_rgb, cv2.COLOR_BGR2GRAY)
- if new_path:
- cv2.imwrite(new_path, pic_path_gray)
- return pic_path_gray
-
-
- def canny_edge(image_array, new_path=''):
- # 灰度图锐化
- can = cv2.Canny(image_array, threshold1=200, threshold2=300)
- if new_path:
- cv2.imwrite(new_path, can)
- return can
-
-
- # 获取灰度图
- gray_path = r"jietu_1_gray.png"
- image_gray1 = pic2gray(path1, gray_path)
- gray_path = r"jietu_2_gray.png"
- image_gray2 = pic2gray(path2, gray_path)
-
- # 获取锐化后的图片,当实际图片内容复杂时,背景图片和缺口图片的锐化参数应该是不同的
- can_path1 = r"jietu_1_can.png"
- canny_edge(image_gray1, can_path1)
- can_path2 = r"jietu_2_can.png"
- canny_edge(image_gray2, can_path2)
-
- img = cv2.imread(can_path1)
- template = cv2.imread(can_path2)
- # 实行缺口匹配算法
- res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF)
- min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
- print(min_val, max_val, min_loc, max_loc)
-
- h, w = template.shape[:2]
- # h1, w1 = img.shape[:2]
- # print(h1, w1)
-
- left_top = max_loc # 左上角
- right_bottom = (left_top[0] + w, left_top[1] + h) # 右下角
- cv2.rectangle(img, left_top, right_bottom, 255, 2) # 画出矩形位置
-
- plt.subplot(121), plt.imshow(res, cmap='gray')
- plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
-
- plt.subplot(122), plt.imshow(img, cmap='gray')
- plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
- plt.show()
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
运行结果:
可以知道确实找到缺口位置了,done。
参考:
- https://zhuanlan.zhihu.com/p/115317146
- https://www.cnblogs.com/gezhuangzhuang/p/10724769.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。