Using rewind in opencv - python

Is it possible to rewind when you press a designated key in opencv? I have got the below but it does not rewind the playback.
def run(self, filepath, fps, width, height, monochrome=False):
video_file = self.read_file(filepath)
previous_frame = None
while (video_file.isOpened()):
ret, frame = video_file.read()
if previous_frame is not None:
pass
previous_frame = frame
if ret:
frame = self.color(frame, monochrome)
final_frame = self.resolution(frame, width, height)
delaytime = self.frame_per_second(fps)
cv2.imshow('frame', final_frame)
key = cv2.waitKey(delaytime)
if key & 0xFF == ord("p"):
cv2.waitKey(234320)
if key & 0xFF == ord("r"):
cv2.set(cv2.CV_CAP_PROP_POS_FRAMES(2, previous_frame))
video_file.release()
cv2.destroyAllWindows()
The above code takes it to the previous frame but does not play.

The ideal solution is to set the frame number that needs to played when the video is paused to achieve the rewind effect. This can be done through video capture properties:
cv2.VideoCapture.set(propId, value)
CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
Helpful examples are available at "Jumping between frames in video files".
This is a source code example that pauses the video and provides some control to let you rewind to the previous frame or jump to frame zero and restart the video:
import cv2
import sys
# load input video
cap = cv2.VideoCapture('TheMandalorian.mkv')
if (cap.isOpened() == False):
print("!!! Failed cap.isOpened()")
sys.exit(-1)
# retrieve the total number of frames
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# loop to read every frame of the video
while (cap.isOpened()):
# capture a frame
ret, frame = cap.read()
if ret == False:
print("!!! Failed cap.read()")
break
cv2.imshow('video', frame)
# check if 'p' was pressed and wait for a 'b' press
key = cv2.waitKey(int(frame_count/1000))
if (key & 0xFF == ord('p')):
# sleep here until a valid key is pressed
while (True):
key = cv2.waitKey(0)
# check if 'p' is pressed and resume playing
if (key & 0xFF == ord('p')):
break
# check if 'b' is pressed and rewind video to the previous frame, but do not play
if (key & 0xFF == ord('b')):
cur_frame_number = cap.get(cv2.CAP_PROP_POS_FRAMES)
print('* At frame #' + str(cur_frame_number))
prev_frame = cur_frame_number
if (cur_frame_number > 1):
prev_frame -= 1
print('* Rewind to frame #' + str(prev_frame))
cap.set(cv2.CAP_PROP_POS_FRAMES, prev_frame)
# check if 'r' is pressed and rewind video to frame 0, then resume playing
if (key & 0xFF == ord('r')):
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
break
# exit when 'q' is pressed to quit
elif (key & 0xFF == ord('q')):
break
# release resources
cap.release()
cv2.destroyAllWindows()
Key press options:
Press q to exit the application.
Press p to pause.
When paused, press p again to resume playing.
When paused, press b to rewind a single frame. You must press p to resume playing again.
When paused, press r to rewind back to frame 0 and automatically resume playing.

If you just want the previous frame, it is possible to store in a temporary array.
For example:
prev_frame = curr_image.copy()

Related

PyQt5 MdAria Open camera in the same window

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

How play audio from a video file from specific frame in python

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)

Mouse input outside the window

I am trying to figure out how to replace keyboard press into mouse left click..
I tried pynput, but for somewhat reason it doesn't seem to be working. Can anyone help with this?
IS there a way to receive this input even while doing something else? For example browsing the internet and still getting screenshots when mouse is clicked.
cam = cv2.VideoCapture(1)
cv2.namedWindow("test")
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
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
elif k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()

streaming audio and video in python

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?

Python: Capture image from camera on press space key using OpenCV

I am using the code below to capure frames from the camera when space key is pressed and save the frame to file. This code works OK.
import cv2
cam = cv2.VideoCapture("rtsp://10.0.0.90:554/?chID=1&streamType=main&linkType=tcp")
cv2.namedWindow("test")
img_counter = 0
while True:
ret, frame = cam.read()
cv2.imshow("test", frame)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()
I need your help to edit this code and create new loop where every half second 2 last frames will blink so I can
cv2.imshow('image', previous_frame)
time.sleep(0.5)
cv2.imshow('image', last_frame)
time.sleep(0.5)
So the task is when the programm starts show the first still frame (opencv_frame_0.png). When the space key pressed start flashing 2 images (opencv_frame_0 and opencv_frame_1) every 0.5 sec. When space key pressed again the images that will flash will be opencv_frame_1 and opencv_frame_2.
I am noob in python and opencv and need some help.
Thank you in advance.

Categories

Resources