0

I am trying to write a code where after matching with a given template, the detected part of that frame becomes the template for the next frame.

temp = "image.png" while True: try: _, frame = cap.read() copy = frame.copy()

    w,h=temp.shape[:-1] 
    res=cv2.matchTemplate(frame,temp,cv2.TM_CCOEFF_NORMED)
    
        
    threshold=0.75
#try:
    
    loc=np.where(res>=threshold)
    print(len(loc))

    for pt in zip(*loc[::-1]):
            
            #cv2.rectangle(img,pt,(pt[0]+w,pt[1]+h),(0,255,255),2)
        point = pt
    

    cropped_image = copy[point[1]:point[1]+h, point[0]:point[0]+w]
    
    temp = cropped_image  #update the template

but after writing this code the template matching is going in totally wrong direction, even though if i remove the "temp = cropped_image" then the cropped_image is actually good.

abc123
  • 1
  • Post and example frame and template image to some free hosting service and put the URL here. I am not quite sure I understand you issue – fmw42 Oct 20 '22 at 18:10
  • I actually want to update my templates with the previously matched images for all frames in a video – abc123 Oct 20 '22 at 18:24
  • Rather than finding all matches above some threshold, find the best match. See cv2.minMaxLoc(res). Also use either TM_CORR_NORMED or TM_SQDIFF for matching. Search this forum or Google. I have numerous posts about template matching. – fmw42 Oct 20 '22 at 19:02
  • look at `samples/python/mosse.py` – Christoph Rackwitz Oct 21 '22 at 07:52

1 Answers1

0

You can find x,y,w,h of the matched image with cv2.minMaxLoc()

import cv2

src = cv2.imread("source.png", cv2.IMREAD_GRAYSCALE)
templit = cv2.imread("initial_template.png", cv2.IMREAD_GRAYSCALE)

result = cv2.matchTemplate(src, templit, cv2.TM_SQDIFF_NORMED)

minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result)
x, y = minLoc
h, w = templit.shape

cropped_img = src[y: y + h, x: x + w]

//do template matching again with cropped_image
Lunethan
  • 76
  • 7