OpenCV with Python error for arcLength

2019-08-07 04:35发布

问题:

I have an issue in my code and can't find a proper solution for it. I am using Python 2.7.10 and OpenCV 3.0. I read two images and want to match one of the pictures(a template) with the contours from the other but I get the following error:

error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function cv::arcLength

My code looks like this:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 10, 17)
edges = cv2.Canny(gray, 100, 20)

contours,hierarchy, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    ret = cv2.matchShapes(c, compare, 1, 0.0)
    if ret < 0.5:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)

Both gray and compare images are grayscale. The error is obviously saying that I need my array to be of floats or double, but I got no idea how to convert it in python and I've found many examples with the function working and the code seems almost the same.

Furthermore, in most applications I've noticed that on most examples the findContours() functions returns 2 values, but I get an error if I don't give it 3.

Please help me find the issue!

回答1:

What that error actually means is that your image is in 32 bit floats and not integers. Specifically 8 bit unsigned integers. I believe, this corresponds to a grayscale image as its understood by OpenCV. You can have other types of underlying number types and it will still display in grayscale mode in a viewer but understand that the viewer you use will rescale it (quietly) to display it.

What I can recommend you try is:

gray_image = cv2.convertScaleAbs(img)

Not sure what is going on with the return thing.

Also I apologize, I misread that you're asking for cv2 and you're asking cv3. I think it should be similar enough, give me some time to check it out.

Edit

OpenCV3 has a bit of a different syntax as answered in this question by berak: findContours and drawContours errors in opencv 3 beta/python

opencv 3 has a slightly changed syntax here, the return values differ:

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy


回答2:

Try this:

for c in contours[1]:
    ret = cv2.matchShapes(c, compare, 1, 0.0)
    if ret < 0.5:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)