Simple OpenCV Test only shows first frame - python

this simple python script should show continually the webcam video but it only shows the first frame.
import cv2
print('cv2 version is ' + str(cv2.getVersionString()))
def capture_config(camera_port=0):
frame_height = 480
frame_width = 640
cap = cv2.VideoCapture(camera_port)
cap.set(3, frame_width)
cap.set(4, frame_height)
if not cap.isOpened():
print('Unable to read camera feed')
return False
return cap
cap = capture_config()
while cap:
ret, frame = cap.read()
cv2.imshow('captured frame', frame)
if cv2.waitKey(0) & 0xff == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
the output is
cv2 version is 4.5.1
It' on ubuntu 20.03 and python 3.8
any valid reason why the script would only show the first frame ?

Related

saving a video with opencv python 3

I want to save a video after converting to gray scale. I don't know where exactly put the line out.write(gray_video). I use jupyter notebook with Python 3, and the Opencv library.
the code is:
import cv2
import numpy as np
video = cv2.VideoCapture("video1.mp4")
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('out_gray_scale.mp4', fourcc, 10.0, (640, 480),0)
while (True):
(ret, frame) = video.read()
if not ret:
print("Video Completed")
break
# Convert the frames into Grayscaleo
gray_video = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#writing
gray_frame = cv2.flip(gray_video, 0)
out.write(gray_video) #it suppose to save the gray video
#Show the binary frames
if ret == True:
cv2.imshow("video grayscale",gray_video)
#out.write(gray_video)
# Press q to exit the video
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
video.release()
cv2.destroyAllWindows()
The working video writer module of OpenCV depends on three main things:
the available/supported/installed codecs on the OS
getting the right codec and file extension combinations
the input video resolution should be same as output video resolution otherwise resize the frames before writing
If any of this is wrong openCV will probably write a very small video file which will not open in video player. The following code should work fine:
import cv2
import numpy as np
video = cv2.VideoCapture("inp.mp4")
video_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) # float `width`
video_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) # float `height`
video_fps = int(video.get(cv2.CAP_PROP_FPS))
print(video_width, video_height, video_fps)
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
out = cv2.VideoWriter('out_gray_scale1.avi', fourcc, video_fps, (video_width, video_height),0)
while (True):
ret, frame = video.read()
if not ret:
print("Video Completed")
break
# Convert the frames into Grayscale
gray_video = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#Show the binary frames
if ret == True:
cv2.imshow("video grayscale",gray_video)
#Writing video
out.write(gray_video)
# Press q to exit the video
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
video.release()
out.release()
cv2.destroyAllWindows()

failing to play the whole video using cv2

i am trying to play a video using cv2 but it's only showing one frame and the video disappears
import cv2
img_file = 'car image.jpg'
video = cv2.VideoCapture('Tesla Dashcam AccidentTrim.mp4')
while True:
(read_successful, frame) = video.read()
if read_successful:
grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
break
classifier_file = 'car_detector.xml'
#Display the image with the faces spotted
cv2.imshow('Newton Caffrey Face Detector', grayscaled_frame)
#Don't Autoclose here (wait here in the code and listen for a key press)
cv2.waitKey(1)
I used the following code for displaying the video using cv2. It will keep displaying frames untill video ends. hope this will work for you, peace!
import cv2
cap = cv2.VideoCapture("Video.mp4")
width = 400
height = 300
num = 0
while True:
ret, frame = cap.read()
if ret:
frame = cv2.resize (frame, (width, height))
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xff == ord('q'):
break
cv2.destroyAllWindows()

Video written through OpenCV on Raspberry Pi not running

I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code
import cv2
cap = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'')
out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480))
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF== ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The video file is created but I am not able to run that file. I also tried with different formats like 'XVID','MJPG','H264' but faced the same issue.
My opencv version is 4.3.038
There are two issues, I would like to address:
Issue #1: DIVX should be declared as:
fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
Issue #2:
You have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480)
frame = cv2.resize(frame, (640, 480))
But if you use it with DIVX you will have a warning:
OpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Instead of DIVX use mp4v for creating .mp4 videos.
Code:
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('output.mp4', fourcc, 25, (640, 480), isColor=True)
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (640, 480))
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
You can try this code. Works for me
import cv2
cap = cv2.VideoCapture(0)
video_speed = 15 #This frame rate works well on my case
video_name = 'output.avi'
writer = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc('M','J','P','G'),video_speed, (640,480))
while True:
ret , frame = cap.read()
if ret == True:
writer.writer(frame)
cv2.imshow('Frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
cap.release()
writer.release()
cv2.destroyAllWindows()

Why isn't the video feed read by the web camera in python code?

When I run my python opencv code, the web camera does not read a video feed. There are no any errors, but the black color output with wifi sign and loading sign i there. How to fix that and read the video feed. Here is my code and the output.
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))
print(cap.isOpened())
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out.write(frame)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
If you are only using one camera you can try the following:
cap = cv2.VideoCapture(-1)
This will pick up the first webcam the system can find.
How are you overlaying the wifi/loading signs - I assume they are not part of the webcam feed?

Cannot Close Video Window in OpenCV

I would like to play a video in openCV using python and close that window at any time, but it is not working.
import numpy as np
import cv2
fileName='test.mp4' # change the file name if needed
cap = cv2.VideoCapture(fileName) # load the video
while(cap.isOpened()):
# play the video by reading frame by frame
ret, frame = cap.read()
if ret==True:
# optional: do some image processing here
cv2.imshow('frame',frame) # show the video
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
The window opens and starts playing the video, but I cannot close the window.
You can use cv2.getWindowProperty('window-name', index) to detect if the window is closed. I'm not totally sure about the index but this worked for me:
import cv2
filename = 'test.mp4'
cam = cv2.VideoCapture(filename)
while True:
ret, frame = cam.read()
if not ret:
break
cv2.imshow('asd', frame)
cv2.waitKey(1)
if cv2.getWindowProperty('asd', 4) < 1:
break

Categories