I have this python code that detects correctly one template and all their occurrences in…
- User
I have this python code that detects correctly one template and all their occurrences in the same image, but I want to modify it to receive several templates as input and detect every template and all their occurrences in the same image
def Detect_Template(image, template, color):
get the width and height of the template image
template_h, template_w = template.shape[:-1]
perform template matching using the normalized cross-correlation method
result = cv2.matchTemplate(image_gray, template_gray, cv2.TM_CCOEFF_NORMED)
set a threshold value for the matches
threshold = 0.70
find all local maxima in the result map that exceed the threshold
(yCoords, xCoords) = np.where(result >= threshold)
initialize our list of rectangles
rects = []
loop over the starting (x, y)-coordinates again
for (x, y) in zip(xCoords, yCoords):
update our list of rectangles
rects.append((x, y, x + template_w, y + template_h))
apply non-maxima suppression to the rectangles
pick = non_max_suppression(np.array(rects)) #print(“[INFO] {} matched locations detected”.format(len(pick)))
loop over the final bounding boxes
for (startX, startY, endX, endY) in pick:
draw the bounding box on the image
cv2.rectangle(image, (startX, startY), (endX, endY), color, 3)
return image
- Assistant
- User
can you repeat the code with spaces? the spaces were deleted
- Assistant
Sure, here is the modified code with added spaces:
- User
it gave me this error:
result = cv2.matchTemplate(image_gray, template_gray, cv2.TM_CCOEFF_NORMED) cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:1104: error: (-215:Assertion failed) (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 in function 'cv::matchTemplate'
- Assistant
The error message suggests that there is an issue with the input data types or dimensions. Here are some things you can check:
-
Make sure that all templates have the same data type and shape as the input image. You can print their data types and shapes using
print(template.dtype)andprint(template.shape). -
Make sure that the input image and templates are 2D arrays of type
uint8orfloat32. You can convert them to this format usingimage.astype(np.uint8)ortemplate.astype(np.uint8). -
If the error persists, you can try to resize the templates to match the size of the input image before performing template matching. Here's an example code:
image = cv2.imread("image.jpg") templates = [cv2.imread("template1.jpg"), cv2.imread("template2.jpg")] # resize templates to match the size of the input image h, w = image.shape[:2] templates_resized = [cv2.resize(template, (w, h)) for template in templates] # detect templates in the input image detections, output_image = Detect_Templates(image, templates_resized, [(0, 255, 0), (0, 0, 255)]) -