what are values returned by findcontour function in opencv 2.4.9

Viewed 15734

i'm using openCV 2.4.9 version and the code i was referring to had the following line: im2,contours,hier=cv2.findContours(im_th.copy(),cv2.RETR_EXTERNAL,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

I keep getting the error : "ValuesError : need more than 2 values to unpack " I understand that findContour in 2.4.9 version of openCV returns only two values. But what are those values ?

2 Answers

In the three parameter version of this function, it returns the additional "im2" parameter. I'll cover contours and hierarchy returns briefly as they are well documented. The two return values depend on the two constants passed in. They are variants on the below.

Contours is a list, or tree of lists of points. The points describe each contour, that is, a vector that could be drawn as an outline around the parts of the shape based on it's difference from a background.

Hierarchy shows how the shapes relate to each other, layers as such - if shapes are on top of each other this can be determined here.

Experimenting with the im2 return value

The documentation at https://docs.opencv.org/3.3.1/d4/d73/tutorial_py_contours_begin.html suggests im2 is a modified image. I'm interested in this one return value because documentation doesn't really tell me what it does or is useful for.

Actual experimentation shows no difference. My code:

import cv2

im = cv2.imread('shapes_and_colors.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.jpg", imgray)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
cv2.imwrite("thresh.jpg", thresh)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.imwrite("contour.jpg", im2)

Shapes and colors is a test image from pyimagesearch:

The original image

This is turned into a greyscale to threshold it:

Image converted to greyscale

I then apply a threshold, to get a binary image:

enter image description here

Finally I run findcontours - and just write the "im2" parameter to an image:

enter image description here

There is no visible difference. Perhaps a sophisticated image diff algorithm could find something I can't. I realise these are lossy JPG's which may confound that. So far, I can't see that the im2 return value serves much of a purpose, but that contours and hierarchy are definitely useful.

I'll say that I'd expected to see something like drawcontours - but there is only one channel in that binary image, so even if it had, I'm not convinced I'd be able to see it. You cannot apply it to 32 bit images in it's normal mode. I also see no visible difference applying to the image in greyscale without thresholding.

Related