Ask Your Question
1

in Python trying to use cv2.matchShapes() from OpenCV

asked 2014-04-11 07:26:39 -0600

Francesco Sgaramella gravatar image

updated 2015-09-25 15:10:02 -0600

I have done a random drawing on a whiteboard and NAO robot has taken a picture and tried to re-create the same drawing.

My drawing:

image description

NAO's drawing:

image description

At this point I would like to write some conclusions about it, specifically I want to extract the contours from both pictures and match the contours using the OpenCV function cv2.matchShapes().

However, I wrote a small Python code script for this and it gives me some errors. Here is the code:

import numpy as np
import cv2

#get the pictures from the forlder
original = cv2.imread('eightgon.jpg')
drawn = cv2.imread('eightgon1.jpg')

#make them gray    
originalGray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
drawnGray = cv2.cvtColor(drawn, cv2.COLOR_BGR2GRAY)

#apply erosion
kernel = np.ones((2, 2),np.uint8)
originalErosion = cv2.erode(originalGray, kernel, iterations = 1)
drawnErosion = cv2.erode(drawnGray, kernel, iterations = 1)

#retrieve edges with Canny
thresh = 175
originalEdges = cv2.Canny(originalErosion, thresh, thresh*2)
drawnEdges = cv2.Canny(drawnErosion, thresh, thresh*2)

#extract contours
originalContours, Orighierarchy = cv2.findContours(originalEdges, cv2.cv.CV_RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
drawnContours, Drawnhierarchy = cv2.findContours(drawnEdges, cv2.cv.CV_RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

print cv2.matchShapes(drawnContours,originalContours,cv2.cv.CV_CONTOURS_MATCH_I1, 0.0)

When I run this simple code, it returns me this error:

File "C:/Python27/getResults.py", line 32, in <module>
    ret = cv2.matchShapes(drawnContours,originalContours,cv2.cv.CV_CONTOURS_MATCH_I1, 0.0)
TypeError: contour1 is not a numpy array, neither a scalar

Since the error tells me that the contours should be arrays.. I make a slight change in the code like this:

cnt1 = np.asarray(drawnContours, np.int0)
cnt2 = np.asarray(originalContours, np.int0)
print cv2.matchShapes(cnt1,cnt2,cv2.cv.CV_CONTOURS_MATCH_I1, 0.0)

and in this case it returns me this error: ValueError: setting an array element with a sequence.

What am I doing wrong? Any help is apreciated!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2014-04-11 07:47:56 -0600

Guanta gravatar image

Afaik findContours gives you a list of contours, i.e. if you know that it gave exactly one contour, compare originalContours[0] w. drawContours[0], otherwise you can compare each possible combination, e.g.

for i in range(len(orginalContours)):
  for k in range(len(drawnContours)):
    print cv2.matchShapes(drawnContours[k],orginalContours[i],cv2.cv.CV_CONTOURS_MATCH_I1, 0.0)
edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-04-11 07:26:39 -0600

Seen: 3,560 times

Last updated: Apr 11 '14