imsanjoykb / Data-Science-Regular-Bootcamp

Regular practice on Data Science, Machien Learning, Deep Learning, Solving ML Project problem, Analytical Issue. Regular boost up my knowledge. The goal is to help learner with learning resource on Data Science filed.
https://imsanjoykb.github.io/
MIT License
109 stars 42 forks source link

OpenCV: Capture Video from Camera #155

Open imsanjoykb opened 2 years ago

imsanjoykb commented 2 years ago
# import the opencv library
import cv2

# define a video capture object
vid = cv2.VideoCapture(0)

while(True):

    # Capture the video frame
    # by frame
    ret, frame = vid.read()

    # Display the resulting frame
    cv2.imshow('frame', frame)

    # the 'q' button is set as the
    # quitting button you may use any
    # desired button of your choice
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
koushik30027 commented 2 years ago

Solution: -

  1. To access the camera, you need to set the path where the images taken from the camera are to be stored.
  2. Make sure you have opencv installed Command : - !pip install opencv-python
  3. Now use the below code : - 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.