Template matching with multiple source images in OpenCV and Python

℡╲_俬逩灬. 提交于 2020-12-29 04:57:33

问题


The following is the code in Python and OpenCV for image detection using template matching

import numpy as np
import cv2

image = cv2.imread('photo.jpg')

template = cv2.imread('template.jpg')

# resize images
image = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 
template = cv2.resize(template, (0,0), fx=0.5, fy=0.5) 

# Convert to grayscale
imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
templateGray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)

# Find template
result = cv2.matchTemplate(imageGray,templateGray, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = max_loc
h,w = templateGray.shape
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(image,top_left, bottom_right,(0,0,255),4)

# Show result
cv2.imshow("Template", template)
cv2.imshow("Result", image)

cv2.moveWindow("Template", 10, 50);
cv2.moveWindow("Result", 150, 50);

cv2.waitKey(0)

I want to know how to do the program with multiple source images?


回答1:


Assuming that you mean multiple template images, here is something I tried.

import cv2
import numpy as np
import glob

#empty list to store template images
template_data=[]
#make a list of all template images from a directory
files1= glob.glob('your\\template images\\template*.png')

for myfile in files1:
    image = cv2.imread(myfile,0)
    template_data.append(image)

test_image=cv2.imread('you\\testimage\\testimage.png')
test_image= cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)

#loop for matching
for tmp in template_data:
    (tH, tW) = tmp.shape[:2]
    cv2.imshow("Template", tmp)
    cv2.waitKey(1000)
    cv2.destroyAllWindows()
    result = cv2.matchTemplate(test_image, tmp, cv2.TM_CCOEFF)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    top_left = max_loc
    bottom_right = (top_left[0] + tW, top_left[1] + tH)
    cv2.rectangle(test_image,top_left, bottom_right,255, 2)

cv2.imshow('Result',test_image)
cv2.waitKey(0)


来源:https://stackoverflow.com/questions/43339287/template-matching-with-multiple-source-images-in-opencv-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!