Get the current frame from USB camera using opencv - python-3.x

I'm using opencv's VideoCapture() to read frames from a USB camera. What I want is getting still images at some random time.
What I have now is that I initialize the cap using:
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
Then use this bit of code to get frame:
ret, frame = cap.read()
I can get the first frame correctly. However, it seems the next time I acquire a frame (after a random time gap), it is not the frame at that time, but the consecutive frame next to the first one (almost the same as the first frame).
I also tried to release the cap after the first time and get a new cap for the second capture. But initialing the cap takes around 1 second, which is too long and cannot be accepted.
Is there any solution to this problem?
Thanks.

A solution is to continually capture frames, but only display a frame after a random time gap.
Wait a random number of frames:
import random
import cv2
cap = cv2.VideoCapture(0)
def wait(delay):
framecount = 0
# capture and discard frames while the delay is not over
while framecount < delay:
cap.read()
framecount += 1
while True:
# select and wait random number of delay frames
delay = random.randint(50,150)
wait(delay)
# get and display next frame
ret, img = cap.read()
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
Random time wait:
import time
import random
import cv2
curr_time = time.time()
cap = cv2.VideoCapture(0)
def wait(delay):
# capture and discard frames while the delay is not over
while time.time()-curr_time < delay:
cap.read()
while True:
# select and wait random delay time
delay = random.random()
wait(delay)
# update curr_time
curr_time = time.time()
# get and display next frame
ret, img = cap.read()
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()

Related

OpenCV do not want to stop video recording with cv2.COLOR_BGR2GRAY

when i run this code:
from cv2 import *
image = cv2.VideoCapture(0, cv2.CAP_DSHOW)
fourcc_cod = cv2.VideoWriter_fourcc(*"XVID")
name = input()
video = cv2.VideoWriter(f"{name}.AVI",fourcc_cod,60,(640,480))
while (True):
check,frame = image.read()
frame1 = cvtColor(frame, cv2.COLOR_BGR2GRAY)
video.write(frame1)
cv2.imshow('myimage',frame1)
if waitKey(1) ord('q'):
cv2.destroyAllWindows()
video.release()
image.release()
it does not stop recording the video Even if I press "q"
Try this snippet.
import cv2
cap = cv2.VideoCapture(0)
name = input()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(f'{name}.avi', fourcc, 20.0, (640, 480))
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 0)
# uncomment belove line for grayscale
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# write the flipped frame
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release() # video file writer
cv2.destroyAllWindows()

Detect a key pressed in dlib.image_window()

Having the following code:
import dlib
import cv2
from lib.capture import Capture
win = dlib.image_window()
cap = Capture() # Capture image from webcam
cap.start()
while(True):
frame = cap.get() # Get current frame from webcam
if frame is not None:
frame = cv2.flip(frame, 1)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Converting from RGB to BGR (as dlib.image_window requires)
win.set_image(frame) # Display the resulting frame
How can I detect a key pressed e.g. "ESC" in the dlib window???
You can use this:
from msvcrt import getch
import dlib
import cv2
from lib.capture import Capture
win = dlib.image_window()
cap = Capture() # Capture image from webcam
cap.start()
while(True):
frame = cap.get() # Get current frame from webcam
if frame is not None:
frame = cv2.flip(frame, 1)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Converting from RGB to BGR (as dlib.image_window requires)
win.set_image(frame) # Display the resulting frame
key = ord(getch())
if key == 27: #ESC
break

I am trying to capture and save a video file by Open-CV but it's not playing

here is my code which i tried. video file is creating after the code run but video file is not playing. i have trouble to understand?
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('C:/Users/DarkLord/Downloads/output1.avi',fourcc, 20,(1920,1000))
while(cap.isOpened()):
ret, frame = cap.read()
out.write(frame)
if ret==True:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
Try this.
It might help
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('C:/Users/DarkLord/Downloads/output1.avi',fourcc, 20,(1920,1000))
out = cv2.VideoWriter('C:/Users/DarkLord/Downloads/output1.avi', -1, 20,(1920,1000))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
The size of your video must be the same as the size of your camera reading frame.
Fix the code like this.
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter(r'C:/Users/DarkLord/Downloads/output1.avi',fourcc, 20,size)
while(cap.isOpened()):
ret, frame = cap.read()
out.write(frame)
if ret==True:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()

Save image in Full HD size using OpenCv Python

When i try to save a image using cv2.imwrite() method, it save a file in 640x480 pixel size. My web cam is FUll HD (1920×1080 px). How can i save the picture in this FHD size.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame', frame)
cv2.imwrite('a.jpg',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
cap.set(3, 1920)
cap.set(4, 1080)
cap.set(6, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame', frame)
cv2.imwrite('a.jpg',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

How to save video Python 3.5

I have a video 256x300 uint8 (gray). I am tracking an object and displaying a rectangle in the video. I'd like to save that video (with the rectangle displayed). I tried some examples but they are all for RGB video.
import cv2
import sys
import subprocess as sp
if __name__ == '__main__' :
# Set up tracker.
# Instead of MIL, you can also use
# BOOSTING, KCF, TLD, MEDIANFLOW or GOTURN
tracker = cv2.Tracker_create("MIL")
# Read video
video = cv2.VideoCapture("videotest.avi")
# Exit if video not opened.
if not video.isOpened():
print("Could not open video")
sys.exit()
# Read first frame.
ok, frame = video.read()
if not ok:
print("Cannot read video file")
sys.exit()
# Define an initial bounding box
bbox = (90, 10, 30, 30)
# Uncomment the line below to select a different bounding box
# bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
while True:
# Read a new frame
ok, frame = video.read()
if not ok:
break
# Update tracker
ok, bbox = tracker.update(frame)
# Draw bounding box
if ok:
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (0,0,255))
# Display result
cv2.imshow("Tracking", frame)
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
if k == 27 : break
video.release()
cv2.destroyAllWindows()

Resources