Nicholas Bissessar
Nicholas Bissessar

Reputation: 71

How to template match inside a contour?

In an image I have retrieved some rectangular contours of areas that I am interested in and now I would like to match what is inside that area with a template. I have multiple templates but each rectangle would contain at most 3 matching templates and minimum 1 matching template. How exactly do I go about matching the template to only what is inside the rectangle?

if(numberVert == 4):
    #Creating a mask to retrieve only what is inside the block
    blockMask = cv2.rectangle(blockMask, (rx, ry), (rx + rw, ry + rh), (255, 255, 255), FILLED)
    #ANDing it with the inverted color filtered image mask
    blockMask = cv2.bitwise_and(cv2.bitwise_not(imgMask), blockMask)
    #Checking inside the templates list to see which image template matches
    for t in range(len(templates)):
        imgTemp = templates[t]
        #Getting the template width and height
        iw, ih = imgTemp.shape[::-1]
        #Attempting to match template to what is inside the blockMask
        res = cv2.matchTemplate(blockMask, imgTemp, cv2.TM_CCOEFF_NORMED)
        #Defined a threshold to establish a baseline for what may be a match
        tempThresh = 0.65
        #Get location where the match is greater than the threshold
        loc = np.where(res >= tempThresh)
        for pt in zip(*loc[::-1]):
            #Draw possible matches
            cv2.rectangle(srcImg, pt, (pt[0] + iw, pt[1] + ih), (0,0,0), 2)

Upvotes: 1

Views: 507

Answers (1)

gilad eini
gilad eini

Reputation: 387

The approach is the same: replace youר full image with the sub image of the contour and match the template in the sub image

x0, y0 = top_left
x1, y1 = bottom_right
# if the contour is defined by x,y,w,h fix x1=x+w and y1=y+h
sub_img_bgr = original_img_bgr[y0:y1, x0:x1]  # this is your new image
# convert to gray
result = cv2.matchTemplate(sub_img_gray, template_g, method_idx)

enter image description here

Upvotes: 1

Related Questions