Could not collect images for labeling and training

`>
the code

  import cv2 
  import os
  import time
  import uuid

  IMAGES_PATH = 'Tensorflow/workspace/images/collectedimages'
  labels = ['hello', 'thanks', 'yes', 'no', 'IloveYou']
   number_imgs = 15

 for label in labels:
!mkdir {'Tensorflow\workspace\images\collectedimages\\'+label}
cap = cv2.VideoCapture(0)
print('collecting image for {}'.format(label))
time.sleep(2)
for imgnum in range(number_imgs): 
    ret, frame = cap.read()
    imgname = os.path.join(IMAGES_PATH, label, label+'.'+'{}.jpeg'.format(str(uuid.uuid1())))
    cv2.imwrite(imgname, frame)
    cv2.imshow('frame', frame)
    time.sleep(5)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    cap.release()
the error
error                                     Traceback (most recent call last)
<ipython-input-6-8ea005f6434e> in <module>
        7         ret, frame = cap.read()
        8         imgname = os.path.join(IMAGES_PATH, label, label+'.'+'{}.jpeg'.format(str(uuid.uuid1())))
  ----> 9         cv2.imwrite(imgname, frame)
        10         cv2.imshow('frame', frame)
        11         time.sleep(5)

error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-i1s8y2i1\      opencv\modules\imgcodecs\src\loadsave.cpp:753: error: (-215:Assertion failed) !_img.empty()  in function 'cv::imwrite'

real time object detection project

The error shows your image writed by cv2.imwrite is empty and cv2.VideoCapture(0) caputres the image from the first camera device. Please check the camera run normally and make sure the image captured by camera is correct.

1 Like

ALWAYS check if ret is True:

if not ret:
    break

that would have avoided the error.

oh, and your code will still not do what you want. time.sleep(5) is useless because the camera will still produce frames, which will be stale by the time you read them.

1 Like

Thank you for replying…well it capture one image into the assigned folder then the pop up which capture the image goes to not responding …could it be a hardware issue cause Im using my laptops webcam?

Please check cap.release() which is in the for loop and VideoCapture will be released by it and not capture image anymore. Moreover, cv2.waitKey(1) code can delay the video capture stream. It’s no need to use time.sleep to delay.

it can’t. the camera will produce frames regardless. when you wait, say 5 seconds, no matter how, you will get the next frame, which will be 5 seconds old, i.e. “stale”.

waitKey() is preferable to sleep because it doesn’t cause the GUI to lock up.