I have my main image:
And my template:
However, the cv2 code that i am using is not generating the rectangle to show that there is a match, but I am also receiving 0 errors.
Here is the code:
# Read the main image
img_rgb = cv2.imread('main.png')
# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# Read the template
template = cv2.imread('temp.png',0)
template = np.array(template[:,::-1])
# Store width and height of template in w and h
w, h = template.shape[::-1]
# Perform match operations.
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
# Specify a threshold
threshold = 0.8
# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold)
# Draw a rectangle around the matched region.
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)
# Show the final image with the matched area.
cv2.imshow('Detected',img_rgb)
cv2.waitKey()
cv2.destroyAllWindows()
My initial thoughts are that the template image is too large to match with the main, however this is my first go with cv2 and I am unsure how to fix it.
The template matching code I have always matches the dimensions of the template to the dimensions of the image. In your case, where you've already converted the source images to grayscale, change
template = np.array(template[:,::-1])
w, h = template.shape[::-1]
(which might not be doing what you intend anyway) to
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
w, h = template.shape
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.