failing to play the whole video using cv2 - python

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()

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()

How to solve Opencv VideoWriter issues with global variables

I'mm writing this piece of python to display a stream of video from my webcam while at the same time record the video - which I've got working, however I've grayscaled the video streaming to my screen and time stamped it - but my recorded video is in colour! I've included the code below - I've tried using some global variables but nothing worked - any help, greatly appreciated
import cv2
import numpy as np
import time, datetime
import os
genericfilename = "recording"
filetime = str(time.time())
extension = '.avi'
filename = genericfilename + filetime +extension
frames_per_second = 100
res = '720p'
print("NEW FILE NAME: " + filename)
# Set resolution for the video capture
def change_res(cap, width, height):
cap.set(3, width)
cap.set(4, height)
# Standard Video Dimensions Sizes
STD_DIMENSIONS = {
"480p": (640, 480),
"720p": (1280, 720),
"1080p": (1920, 1080),
"4k": (3840, 2160),
}
# grab resolution dimensions and set video capture to it.
def get_dims(cap, res='1080p'):
width, height = STD_DIMENSIONS["480p"]
if res in STD_DIMENSIONS:
width,height = STD_DIMENSIONS[res]
## change the current caputre device
## to the resulting resolution
change_res(cap, width, height)
return width, height
# Video Encoding, might require additional installs
VIDEO_TYPE = {
'avi': cv2.VideoWriter_fourcc(*'XVID'),
#'mp4': cv2.VideoWriter_fourcc(*'H264'),
'mp4': cv2.VideoWriter_fourcc(*'XVID'),
}
def get_video_type(filename):
filename, ext = os.path.splitext(filename)
if ext in VIDEO_TYPE:
return VIDEO_TYPE[ext]
return VIDEO_TYPE['avi']
capture = cv2.VideoCapture(0)
out = cv2.VideoWriter(filename, get_video_type(filename), 60,
get_dims(capture, res))
while(True):
ret, frame = capture.read()
out.write(frame)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
font = cv2.FONT_ITALIC = 1
cv2.putText(grayFrame, str(datetime.datetime.now()), (-330, 460), font, 3,
(200, 200, 200), 2, cv2.LINE_AA)
cv2.imshow('combilift output', grayFrame)
# Press Q on keyboard to exit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if cv2.waitKey(1) & 0xFF == ord('r'):
print(datetime.datetime.now())
capture.release()
out.release()
cv2.destroyAllWindows()
You save the frame to video, then convert frame to gray.
out.write(frame)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
If you want your recorded video to be gray, maybe reverse the order of operations and save grayFrame?
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(grayFrame)
If you want to also save the texts, put the text before writing frame to output.
Lets take a look at ur code
out = cv2.VideoWriter(filename, get_video_type(filename), 60,
.....
while(True):
ret, frame = capture.read()
out.write(frame)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
You first save out then convert color
The correct sequence should be
out = cv2.VideoWriter(filename, get_video_type(filename), 60,
.....
while(True):
ret, frame = capture.read()
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(grayFrame)
I don't have data to test. Just in case you experience some issue with channels. You can use opencv merge(grayFrame,grayFrame,grayFrame) to create a normal 3 channel grey scale image and save to video

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

opencv saved video very faster plaing

I capture video from my camera, but when i save this i received very fast video. Can i capture video with original frame rate?
import cv2
import time
# exit(1)
cap = cv2.VideoCapture("rtsp://192.168.0.66/live1.sdp")
ps = cap.get(cv2.CAP_PROP_FPS)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float
# Get current height of frame
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float
fourcc = cv2.VideoWriter_fourcc(*'XVID')
FILE_OUTPUT = 'out.avi'
FPS = 20.0
cap.set(cv2.CAP_PROP_FPS, FPS)
out = cv2.VideoWriter(FILE_OUTPUT, fourcc, FPS, (int(width), int(height)))
while (True):
ret, frame = cap.read()
if ret == True:
# Write the frame into the file 'output.avi'
out.write(frame)
# Display the resulting frame
cv2.imshow('frame', frame)
# cv2.waitKey(100)
# Press Q on keyboard to stop recording
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Break the loop
else:
break
# When everything done, release the video capture and video write objects
cap.release()
out.release()
# Closes all the frames
cv2.destroyAllWindows()
P.S i use opencv 4 and python3. I try change waitKey option but it had no effect

Stream video from drone Parrot 2.0. Python + cv2

I am trying to have access to the stream of my drone's camera.
Here my code:
import cv2
import numpy
import libardrone
drone = libardrone.ARDrone()
cap = drone.image
while(True):
cap = drone.image
if not cap:
continue
ret, frame = convert
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
It does not work. It does not open any frame where I can see the stream video of my drone's camera.
What's wrong? Do you have any suggestions?
Thank you!
import cv2
cam = cv2.VideoCapture('tcp://192.168.1.1:5555')
running = True
while running:
# get current frame of video
running, frame = cam.read()
if running:
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == 27:
# escape key pressed
running = False
else:
# error reading frame
print 'error reading video feed'
cam.release()
cv2.destroyAllWindows()
Try this code...This works for me.

Categories