Template matching python error

asked 2016-03-12 04:52:11 -0500

adamsss gravatar image

updated 2016-03-12 04:53:42 -0500

Hello, I would like to use this code in my programme:

img_rgb = image
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = roi
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]):
     cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

cv2.imwrite('res.png',img_rgb)

image and roi are the images (tiff format) readed in earlier part of my code

Now, i got error:

w, h = template.shape[::-1] ValueError: too many values to unpack (expected 2)

Where is the problem?!

edit retag flag offensive close merge delete

Comments

template must be a grayscale img for this to work

berak gravatar imageberak ( 2016-03-12 06:32:58 -0500 )edit

Ok, i corrected it, but now another error:

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
cv2.error: ..\..\..\sources\modules\core\src\matrix.cpp:424: error: (-215) u != 0 in function     cv::Mat::create
adamsss gravatar imageadamsss ( 2016-03-12 10:28:48 -0500 )edit

My code, now:

image_dir='7_7026_polowa.tif'   
image = cv2.imread(image_dir)
..........
img_gray = cv2.imread(image_dir, 0)
template = cv2.imread('template.tif', 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]):
      cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

 cv2.imwrite('res.png',image)
adamsss gravatar imageadamsss ( 2016-03-12 10:30:14 -0500 )edit

Additionally, this code works fine with "test.jpg", but doesn't work with TIF file

adamsss gravatar imageadamsss ( 2016-03-12 10:57:55 -0500 )edit

please check, if your tif was actually loaded (!= None)

berak gravatar imageberak ( 2016-03-13 03:19:24 -0500 )edit

It was loaded correctly. I can show it in grayscale and colour.

adamsss gravatar imageadamsss ( 2016-03-13 04:56:06 -0500 )edit

Any ideas?

adamsss gravatar imageadamsss ( 2016-03-22 01:35:27 -0500 )edit