简体   繁体   中英

Detect and Draw Contours with opencv

I have this error in my console:

File "c:/Users/Usuario/Documents/Deteccion de Objetos/contornoscongranny.py", line 13, in <module>
    cv2.drawContours(img, ctns, -1, (0, 0, 255), 2)
cv2.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'

this is my code:

import cv2
import numpy as np

camino= "C:/Users/Usuario/Documents/Deteccion de Objetos/123.jpg"
img = cv2.imread("C:/Users/Usuario/Documents/Deteccion de Objetos/123.jpg")

grises= cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

bordes= cv2.Canny(grises, 100, 200)

_, ctns, = cv2.findContours(bordes, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(img, ctns, -1, (0, 0, 255), 2)
print ('Numero de contornos es ', len(ctns))
texto= 'Contornos encontrados ' + str(len(ctns))

cv2.putText(img, texto, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7,  
    (255, 0, 0), 1)


cv2.imshow('Bordes', bordes)
cv2.imshow('Imagen', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

how can i resolve it?

For drawing the contours, we can use:

ctns = cv2.findContours(bordes, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
ctns = ctns[0] if len(ctns)==2 else ctns[1]
for c in ctns:
    cv2.drawContours(img,[c], -1,(0,0,255),2)

This will draw the contours on the image. If you can share a sample image on which you are trying to make the contours, I would be able to help more

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM