I have following image preprocessed:
Now I want to use findContours
method in order to find cells from image and then use drawContours
in order draw contour for every cell from image. I do this but nothing is shown.
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
I receive the following error.
contours is not a numpy array, neither a scalar
Another answers didn't helped me.
I also use following solution.
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
ctr = numpy.array(contours).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(img, ctr, -1, (0, 255, 0), 3)
But this solution didn't draw anything on the given image.
Update , OpenCV 4.0 change the cv2.findContours
. So I modify the code example. And a more general way:
cnts, hiers = cv2.findContours(...)[:-2]
cv2.findContours
returns a tuple, not just the contours. You can do like this:
## Find contours
if cv2.__version__.startswith("3."):
_, contours, _ = cv2.findContours(bimg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
contours, _ = cv2.findContours(bimg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
## Draw contours
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
Related similar questions:
(1) Python Opencv drawContour error
(2) How to use `cv2.findContours` in different OpenCV versions?
The tuple returned by cv2.findContours
has the form (im, contours, hierarchy)
where im
is the image with contours visualized, contours
is a tuple of two numpy arrays in the form (x_values, y_values)
and heirarchy
depends on the retrieval mode. Since you are using CV_RETR_EXTERNAL, heirarchy
doesn't have much significance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.