Python OpenCV Template Matching with Binarized Template
import cv2
import numpy as np
# Read the original image and the template image
img = cv2.imread('image.jpg', 0)
template = cv2.imread('template.jpg', 0)
# Binarize the template image
_, template = cv2.threshold(template, 127, 255, cv2.THRESH_BINARY)
# Perform edge detection on the original image
edges = cv2.Canny(img, 100, 200)
# Perform template matching using the binarized template
result = cv2.matchTemplate(edges, template, cv2.TM_CCOEFF_NORMED)
# Set the matching threshold
threshold = 0.8
loc = np.where(result >= threshold)
# Draw rectangles on the original image to mark the matching positions
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + template.shape[1], pt[1] + template.shape[0]), (0, 255, 0), 2)
# Display the result
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this code, I have added the binarization step for the template image using the cv2.threshold() function. The binarization threshold is set to 127, which means any pixel value greater than or equal to 127 will be set to 255 (white), and any pixel value below 127 will be set to 0 (black).
原文地址: https://www.cveoy.top/t/topic/l5mP 著作权归作者所有。请勿转载和采集!