Ask Your Question
0

Error while working with contours

asked 2019-10-08 05:52:43 -0600

sth gravatar image

updated 2019-10-08 06:25:40 -0600

berak gravatar image

when running this code

import numpy as np
import cv2

image=cv2.imread('screenshoot10.jpg')
cv2.imshow('input image', image)

gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

edged=cv2.Canny(gray,30,200)
cv2.imshow('canny edges',edged)

_, contours = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
cv2.imshow('canny edges after contouring', edged)

print(contours)
print('Numbers of contours found=' + str(len(contours)))

cv2.drawContours(image,contours,-1,(0,255,0),3)
cv2.imshow('contours',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

getting an error

OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\imgproc\src\drawing.cpp:2509: error: (-215:Assertion failed) npoints > 0 in function 'cv::drawContours'

what am I doing wrong?

edit retag flag offensive close merge delete

Comments

You are missing one or two algorithms in order to get drawContours working

supra56 gravatar imagesupra56 ( 2019-10-08 21:23:45 -0600 )edit

2 answers

Sort by ยป oldest newest most voted
2

answered 2019-10-10 08:24:10 -0600

nicolasabril gravatar image

You are trying to draw the hierarchy instead of the contours. The return of findContours is contours, hierarchy. Therefore, your line _, contours = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) should actually be contours, _ = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE).
Hope it helps.

edit flag offensive delete link more

Comments

it is, it helped me

sth gravatar imagesth ( 2019-10-13 16:46:14 -0600 )edit
-1

answered 2019-10-09 12:34:22 -0600

supra56 gravatar image

Here is code:

import cv2
import numpy as np

image = cv2.imread('sunflower.png')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (23, 23), 0)
cv2.imshow("blurred", blurred)

canny = cv2.Canny(blurred, 30, 30)
cnts, _ = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

print(f"Contours in the image, %d" % (len(cnts)))

shape = image.copy()

cv2.drawContours(shape, cnts, -1, (0, 255, 0), 2)

cv2.imwrite('{}.png'.format('sunflower'), shape)

cv2.imshow("Edges", shape)
cv2.waitKey(0)

Output: image description

edit flag offensive delete link more

Comments

You have play around with 2 values cv2.GaussianBlur and cv2.Canny in order to get smooth edges. You may also wantto add threshold if you want to.

supra56 gravatar imagesupra56 ( 2019-10-09 12:37:17 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2019-10-08 05:52:43 -0600

Seen: 8,442 times

Last updated: Oct 10 '19