Video Stream
Video Frame Capture
Is there any way to get these both to run simultaneously? Like making the video stream run in the bg or something.
Video Stream:
def gen(camera):
while True:
frame = camera.get_frame()
yield frame
#eel.expose
def video_feed():
x = VideoCamera()
y = gen(x)
for each in y:
# Convert bytes to base64 encoded str, as we can only pass json to frontend
blob = base64.b64encode(each)
blob = blob.decode("utf-8")
eel.updateImageSrc(blob, 'output')
Frame Capture:
#eel.expose
def CamDetection():
cap = cv2.VideoCapture(1)
img_counter = 0
if True:
ret, frame = cap.read()
if not (cap.isOpened()):
print("failed to grab frame")
# break
# cv2.imshow("test", frame)
# k = cv2.waitKey(1)
# if k%256 == 27:
# # ESC pressed
# print("Escape hit, closing...")
# break
# if k%256 == 32:
# # SPACE pressed
img_name = "SKH_frame.png".format(img_counter)
path = 'F:\Tensorflow\yolov5\webcamimage'
cv2.imwrite(os.path.join(path, img_name), frame)
print("{} written!".format(img_name))
img_counter += 1
cap.release()
Related
I am creating an application in which i need that in one page there is a button and one view. When i click on that button i want to open camera in that view only not separate view of camera. Is it possible? And if yes, please provide me some hint or code. Thank you.
This code opens the camera separately and not in the designated area
enter code here
def onclicked(self):
u_nam = self.txt_name
img_counter = 0
self.cap = cv2.VideoCapture(0)
while self.cap.isOpened():
ret, frame = self.cap.read()
frame = cv2.flip(frame, 1)
if ret == True:
cv2.imshow(' ', frame)
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
#elif k == btn1:
# SPACE pressed
cv2.imwrite("registered/{u_nam}/frame_{img_counter}.jpg", frame)
print("Successfully captured!")
ret, frame = self.cap.read()
img_counter += 1
self.cap.release()
cv2.destroyAllWindows()
I would like to know how I could go about playing audio from a specific position in a video file, using ffpyplayer.
I know how to set the frame I want to start playing at in opencv but not in ffplayer.
Any ideas or suggestions would help a ton. Here is what I have came up with.
import cv2
from ffpyplayer.player import MediaPlayer
video_path=videoName
def PlayVideo(video_path):
font = cv2.FONT_HERSHEY_SIMPLEX
video = cv2.VideoCapture(video_path)
video.set(cv2.CAP_PROP_POS_FRAMES, 7200)
player = MediaPlayer(video_path)
while True:
grabbed, frame = video.read()
audio_frame, val = player.get_frame()
if not grabbed:
print("End of video")
break
if cv2.waitKey(28) & 0xFF == ord("q"):
break
cv2.imshow("Video", frame)
if val != 'eof' and audio_frame is not None:
#audio
img, t = audio_frame
video.release()
cv2.destroyAllWindows()
PlayVideo(video_path)
I am trying to encode and decode a video losslessly using the DCPM technique which states that you send the first frame of a video as it is and then you calculate the difference to the next frame as currentFrame - previousFrame and you send this sequence until the video has been fully encoded. In the first file I do this and it seems to work fine.
Now when I try to decode, I display the first frame and then compute `firstFrame + nextFrame' and display this sequence until the end which should result in the real video since the first frame is sent intact and the next one is the difference between the second frame and the first frame. But as I do this process I get a bunch of noise and the video isn't decoded losselessly. Why is that?
Below is the encoder
import cv2
import numpy as np
video = cv2.VideoCapture('video.mp4')
previous_frame = None
video_codec = cv2.VideoWriter_fourcc(*'XVID')
# Setup the output
output = cv2.VideoWriter('dpcm_encoded_video.avi', video_codec, int(video.get(5)),
(int(video.get(3)), int(video.get(4))), False)
if not video.isOpened():
print("Error while trying to play the video.")
i = 0
while video.isOpened():
not_exception, current_frame = video.read()
if not_exception:
if previous_frame is None: # First iteration
current_frame = cv2.cvtColor(current_frame, cv2.COLOR_RGB2GRAY)
previous_frame = current_frame
output.write(current_frame)
continue
if i <= 217: #Video is 217 frames
current_frame = cv2.cvtColor(current_frame, cv2.COLOR_RGB2GRAY)
i += 1
difference = current_frame - previous_frame
cv2.imshow('Error frames', difference)
output.write(difference)
previous_frame = current_frame
if cv2.waitKey(10) == ord('q'):
break
else:
break
video.release()
cv2.destroyAllWindows()
And the decoder
import cv2
# Load video
video = cv2.VideoCapture('dpcm_encoded_video.avi')
# Load the first frame of the video
success, first_frame = video.read()
first_frame = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)
# Set video codec
video_codec = cv2.VideoWriter_fourcc(*'XVID')
# Setup the output
output = cv2.VideoWriter('dpcm_decoded_video.avi', video_codec, int(video.get(5)), (int(video.get(3)), int(video.get(4))), False)
output.write(first_frame)
frame_num = 0
previous_frame = first_frame
while video.isOpened():
# Skip the first frame because we load it outside the loop
if frame_num == 0:
#success, current_frame = video.read()
frame_num += 1
continue
success, current_frame = video.read()
frame_num += 1
if not success:
break
# Frame to BW
current_frame = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
# Sum frames
current_frame = previous_frame + current_frame
previous_frame = current_frame
output.write(current_frame)
video.release()
output.release()
so I found this code somewhere and I tried running it:
import cv2
from ffpyplayer.player import MediaPlayer
video_path = "video.mp4"
def video_audio(path):
video = cv2.VideoCapture(video_path)
player = MediaPlayer(video_path)
while True:
ret, frame = video.read()
audio_frame, val = player.get_frame()
if not ret:
print("End of video")
break
if cv2.waitKey(28) & 0xFF == ord("q"):
break
cv2.imshow("Video", frame)
if val != 'eof' and audio_frame is not None:
# audio
img, t = audio_frame
video.release()
cv2.destroyAllWindows()
video_audio(video_path)
it does actually play the video and audio, but there is a delay between the two (current audio frame is played ahead of the current video frame)
does anyone know a possible solution to fix that?
I'm trying to convert a video from my camera feed, which has low fps to gray. I have successfully fetched the video now I want to convert it to grayscale.
I've tried basic opencv operations and it isn't working. I get a video file when I open it there is no video.
import cv2
import time
cap = cv2.VideoCapture('output.avi')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
print(fourcc)
out = cv2.VideoWriter('grey.avi',fourcc, 30.0, (800,600))
while True:
ret, frame = cap.read()
time.sleep(0.1)
cv2.imshow('frame1',frame)
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
out.write(frame)
cv2.imwrite('img.jpg',frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
You need to change the isColor flag in cv2.VideoWriter. Currently the video writer setting is set to color instead of gray scale. You're incorrectly attempting to save a 3-channel color image (OpenCV default is BGR) as a gray scale image.
Change
out = cv2.VideoWriter('grey.avi',fourcc, 30.0, (800,600))
to
out = cv2.VideoWriter('grey.avi',fourcc, 30.0, (800,600), isColor=False)
Also your overall goal seems to capture video from a stream/camera feed and save the captured video in gray scale format. Here's an 'all in one' widget that reads frames from a camera stream link (RTSP), converts each frame to gray scale, and saves it as a video. Change video_src to your camera stream link.
from threading import Thread
import cv2
class VideoToGrayscaleWidget(object):
def __init__(self, src=0):
# Create a VideoCapture object
self.capture = cv2.VideoCapture(src)
# Default resolutions of the frame are obtained (system dependent)
self.frame_width = int(self.capture.get(3))
self.frame_height = int(self.capture.get(4))
# Set up codec and output video settings
self.codec = cv2.VideoWriter_fourcc('X','V','I','D')
self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height), isColor=False)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
def show_frame(self):
# Convert to grayscale and display frames
if self.status:
self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('grayscale frame', self.gray)
# Press 'q' on keyboard to stop recording
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
self.output_video.release()
cv2.destroyAllWindows()
exit(1)
def save_frame(self):
# Save grayscale frame into video output file
self.output_video.write(self.gray)
if __name__ == '__main__':
video_src = 'Your video stream link!'
video_stream_widget = VideoToGrayscaleWidget(video_src)
while True:
try:
video_stream_widget.show_frame()
video_stream_widget.save_frame()
except AttributeError:
pass