TheRocinante
TheRocinante

Reputation: 4201

Using CV2 in Python to find two instances of image within image

import cv2
import numpy as np
import Image

image = cv2.imread("haystack.bmp")
needle = cv2.imread("needle.bmp")

result = cv2.matchTemplate(image,needle,cv2.TM_CCOEFF_NORMED)
y,x = np.unravel_index(result.argmax(),result.shape)

print x, y

This is the code I have currently that will find needle in the haystack. and give me the x,y coordinates. However, the needle will always occur in the haystack two times. I would like to get the second pair of x,y coordinates as well. I've only found one other post on StackOverflow discussing this, and its solution only confused me and didn't work.

Edit: Here's what I ended up doing...

    img_rgb = cv2.imread('haystack.bmp')
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread('needle.bmp',0)
    w, h = template.shape[::-1]

    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where( res >= threshold)

    for pt in zip(*loc[::-1]):
        # print pt - pt contains the coordinates I need
        cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

Upvotes: 0

Views: 1565

Answers (1)

Rosa Gronchi
Rosa Gronchi

Reputation: 1911

One option would be to set the value of the result cv::Mat to zero in a small region - possibly the size of needle, around x,y (the coordinates of the first result) and call: y1,x1 = np.unravel_index(result.argmax(),result.shape)

Upvotes: 1

Related Questions