如果我想从一张图片上,把所有的相同图案的地方查找出来,该如何处理呢?今天小编就来处理这个问题。
比如有这样的一张图片,上面有几张扑克牌,我们想找出所有的红色方片图案。

我们直接上干货:
新建文件same_obj.py
import cv2
import numpy as np
#特征提取, 模板匹配, 识别所有的方片牌
image = cv2.imread('./images/poker.png')
print(image.shape)
#转灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
template = gray[40:82,275:325]
match = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
print(match.shape)
locations = np.where(match >= 0.9)
# print(match)
w,h = template.shape[:2]
for p in zip(*locations[::-1]):
x1,y1 = p[0], p[1]
x2,y2 = x1 + w, y1 + h
cv2.rectangle(image, (x1,y1), (x2,y2), (0, 255, 0), 2)
cv2.imshow("image", image)
# 等待按键输入
cv2.waitKey()
cv2.destroyAllWindows()
运行效果图如下:

我们可以可以看到所有的红色方片都被找了出来。

全部评论