Q: Error when I try to use my webcam (python) So, I'm using jupyter in a facial detection project, and when I run the program , this message error appears:
> (error: OpenCV(4.2.0)
> C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182:
> error: (-215:Assertion failed) !_src.empty() in function
> 'cv::cvtColor') [enter image description here][1]


This is the code:


Thank you !

A: This error happens when frame is empty = image was not captured. You are not checking if video_capture is correctly opened before using video_capture.read(). Try to check if read() returned frame:
...
retval, frame = video_capture.read()
if (!retval):
   print("Error when capturing frame")
   continue # loop until retval is true

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

The problem can have more causes:


*

*camera is not responding

*there are more cameras and you initialized wrong camera id 

*camera is slow and first few frames are empty/not read


You can identify if it is faulty camera by loading picture with cv2.imread() before cv2.cvtColor() into frame and processing it, if it works, then try to troubleshoot video_capture initialization and camera.
TL;DR: frame is empty when calling cv2.cvtColor(), ensure/check that it isn't

A: import cv2 
import uuid
import os
import time
labels = ['pistol','knife','rifle','shotgun']
number_imgs = 5

   By using above code lables are created so that pictures will be saved in respective folders and number_imgs is number of images to be taken.
IMAGES_PATH = os.path.join('Tensorflow', 'workspace', 'images', 'collectedimages')

   By using the above code we are defining the path.
if not os.path.exists(IMAGES_PATH):
if os.name == 'posix':
    !mkdir -p {IMAGES_PATH}
if os.name == 'nt':
     !mkdir {IMAGES_PATH}
for label in labels:
path = os.path.join(IMAGES_PATH, label)
if not os.path.exists(path):
    !mkdir {path}

   The Images path will be created inside virtual environment by using the above code.
for label in labels:
cap = cv2.VideoCapture(0)
print('Collecting images for {}'.format(label))
time.sleep(5)
for imgnum in range(number_imgs):
    print('Collecting image {}'.format(imgnum))
    ret, frame = cap.read()
    imgname = os.path.join(IMAGES_PATH,label,label+'.'+'{}.jpg'.format(str(uuid.uuid1())))
    cv2.imwrite(imgname, frame)
    cv2.imshow('frame', frame)
    time.sleep(2)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break 
cap.release()
cv2.destroyAllWindows()

   By using the above code the camera will open and take pictures and saved them automatically in the specified folders inside the virtual environment.
