Python-OpenCV cv2 OpenCV Error: Asertion failed (scn == 3 || scn == 4) in unknown function, file.....modulesimprocsrccolor.cpp


Estoy tratando de aprender contornos en python usando cv2.

Probé el siguiente código dado en una guía tutorial:

import cv2
import numpy as np
from matplotlib import pyplot as plt

im = cv2.imread('C:\Users\Prashant\Desktop\test.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
img = cv2.drawContour(im, contours, -1, (0,255,0), 3)
cv2.imshow('Image1',img)

Estoy recibiendo este error:

File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in unknown function, file ..\..\..\modules\imgproc\src\color.cpp, line 3402
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
   execfile(filename, namespace)
 File "C:/Users/Prashant/.spyder2/.temp.py", line 15, in <module>
   imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
 cv2.error: ..\..\..\modules\imgproc\src\color.cpp:3402: error: (-215) scn == 3 || scn == 4
Author: Stephen Kennedy, 2013-12-29

3 answers

Dice que la imagen de entrada debe tener 3 o 4 canales antes de aplicar la función cv2.cvtColor.

Así que compruebe la forma de su imagen antes de aplicar la función por print im.shape. si el resultado es None type (la mayoría de las veces, este es el problema), su imagen no se carga correctamente, lo más probable es que su ruta no sea correcta.

El punto es que su imagen debe tener 3 dimensiones, filas, columnas y profundidad.

 81
Author: Abid Rahman K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-29 05:58:05

1st print ret. Si se muestra falso, entonces su imagen no se toma correctamente. Si está mostrando True Pruebe este comando-sudo modprobe bcm2835-v4l2 O en su archivo/etc / modules agregue bcm2835-v4l2 en la parte inferior.

 1
Author: Argha Sen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-30 19:45:19

Si está recibiendo este error en una raspberry PI con cámara PI, intente ejecutar este comando primero:

sudo modprobe bcm2835-v4l2
 0
Author: Xerxel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-01 11:50:33