Ask Your Question
0

Hi I'm using this code in pycharm and I have this error.please help me

asked 2019-09-02 13:41:10 -0600

updated 2019-09-02 14:59:39 -0600

berak gravatar image

import numpy as np import cv2

cap=cv2.VideoCapture(0)
while(True):
    ret,frame=cap.read()
    gray = cv2.cvtColor(frame ,cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) :
        break
cap.release()
cv2.destroyAllWindows()

and the error is:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\imgproc\src\color.cpp, line 9748
Traceback (most recent call last):
  File "D:/python/examples_with_pyCharm/untitled2/Lesson3_VIDEO.py", line 7, in <module>
    gray = cv2.cvtColor(frame ,cv2.COLOR_BGR2GRAY)
cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\imgproc\src\color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
0

answered 2019-09-02 15:04:24 -0600

berak gravatar image

updated 2019-09-02 15:34:18 -0600

it's a typical python nooooooob error. you're blindly pasting other ppls code.

you have to add CHECKS,

  • if the capture could be opened at all: if not cap.isOpened(): ...
  • if it (still) could read an image: if not img is NONE: ...

VideoCapture will NEVER throw any exceptions on failure, so you HAVE to check manually

edit flag offensive delete link more

Comments

Well not throwing any exception was Design by the Open CV Library. It has pros(no stupid exception handling) and cons(its possible to make this error and therefore it will happen).

And yes Java and Python are easy to learn - so some People get a bit "lazy". Btw. you supplied the solution.

holger gravatar imageholger ( 2019-09-02 17:22:25 -0600 )edit
0

answered 2019-09-03 06:42:38 -0600

supra56 gravatar image

In line 7: You can't do this if/else block conditionif cv2.waitKey(1) :. It will shut down in 1 seconds. Correct way to do this.

import cv2 as cv

cap=cv.VideoCapture(0)
while(True):
    ret,frame=cap.read()
    gray = cv.cvtColor(frame ,cv.COLOR_BGR2GRAY)
    cv.imshow('frame',gray)
    key = cv.waitKey(1)
    if key == 27:
        break
cap.release()
cv.destroyAllWindows()

Btw, I'm using Raspberry pi 4 w/4gb, opencv 4.1.0, Thonny3.2, python 3.7.3.

edit flag offensive delete link more

Comments

Btw, Do not use boolean while True: Practically way to do this while cap.isOpened():

supra56 gravatar imagesupra56 ( 2019-09-03 06:48:25 -0600 )edit

Another way to do this:

if cv2.waitKey(1) & 0xFF == ord('q'):
supra56 gravatar imagesupra56 ( 2019-09-03 08:30:17 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2019-09-02 13:41:10 -0600

Seen: 666 times

Last updated: Sep 03 '19