模板匹配
demo1
import cv2
img = cv2.imread("./rh.png")
template = cv2.imread("./template.png")
img = cv2.resize(img, None, None, 0.5, 0.5)
height, width, c = template.shape
result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF_NORMED)
minValue, maxValue, minLoc, maxLoc = cv2.minMaxLoc(result)
resultPoint1 = minLoc
resultPoint2 = (resultPoint1[0] + width, resultPoint1[1] + height)
cv2.rectangle(img, resultPoint1, resultPoint2, (0, 0, 255), 2)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
demo2
import cv2
import os
import sys
PIC_PATH = "./"
width, height = 100, 100
pic_file = os.listdir(PIC_PATH)
same_pic_index = []
imgs = []
has_same = set()
count = len(pic_file)
if count == 0:
print("没有图像")
sys.exit(0)
for file_name in pic_file:
file_name = PIC_PATH + file_name
img = cv2.imread(file_name)
img = cv2.resize(img, (width, height))
imgs.append(img)
for i in range(0, count - 1):
if i in has_same:
continue
templ = imgs[i]
same = [i]
for j in range(0 + i + 1, count):
if j in has_same:
continue
pic = imgs[j]
result = cv2.matchTemplate(pic, templ, cv2.TM_SQDIFF_NORMED)
if result > 0.9:
same.append(j)
has_same.add(i)
has_same.add(j)
if len(same) > 1:
same_pic_index.append(same)
for same_list in same_pic_index:
text = "相同的照片"
for same in same_list:
text += str(pic_file[same]) + ","
print(text)
demo3
import cv2
img = cv2.imread("./orig/hz.jpg")
img = cv2.resize(img, None, None, 0.2, 0.2)
rh = cv2.imread("./template/rh.png")
height, width, c = rh.shape
result = cv2.matchTemplate(img, rh, cv2.TM_CCORR_NORMED)
for y in range(len(result)):
for x in range(len(result[y])):
if result[y][x] > 0.85:
cv2.rectangle(img, (x, y), (x + width, y + height), (0, 0, 255), 2)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
demo4
import cv2
def myMatchTemplate(img, templ):
height, width, c = templ.shape
results = cv2.matchTemplate(img, templ, cv2.TM_CCORR_NORMED)
loc = list()
for i in range(len(results)):
for j in range(len(results[i])):
if results[i][j] > 0.92:
loc.append((j, i, j + width, i + height))
return loc
img = cv2.imread("./orig/hz.jpg")
templs = list()
templs.append(cv2.imread("./template/phl.png"))
templs.append(cv2.imread("./template/rh.png"))
templs.append(cv2.imread("./template/shy.png"))
loc = list()
for t in templs:
loc += myMatchTemplate(img, t)
for i in loc:
cv2.rectangle(img, (i[0], i[1]), (i[2], i[3]), (0, 0, 255), 2)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()