Python CV2 slow response time on keys - python-3.x

I have been coding a video player to test if I can play and pause a video in Python. My problem is that whenever I press a key, its irresponsive and needs continuous presses to work, and the effect is random.
If anyone knows what could be causing this, it would be of great help.
import cv2
cap = cv2.VideoCapture('testvideo.mp4')
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
isPlaying = False
def onchange(trackbar_value):
cap.set(cv2.CAP_PROP_POS_FRAMES, trackbar_value)
err, vid = cap.read()
cv2.imshow('player', vid)
pass
start = 0
cv2.namedWindow('player')
cv2.createTrackbar('test', 'player', start, length, onchange)
onchange(1)
while cap.isOpened():
if cv2.waitKey(1) & 0xFF == ord('q'):
break
elif cv2.waitKey(1) & 0xFF == ord('p'):
isPlaying = not isPlaying
ret, player = cap.read()
if cv2.waitKey(20) == 27:
break
if isPlaying:
cv2.imshow('test', 'frame')
elif cap.get(cv2.CAP_PROP_POS_FRAMES) >= length:
break
cap.release()
cv2.destroyAllWindows()

I fixed it by changing this part in the while cap.isOpened() loop:
keyPress = cv2.waitKey(20)
ret, player = cap.read()
if keyPress & 0xFF == ord('q'):
break
elif keyPress & 0xFF == ord('p'):
isPlaying = not isPlaying
once I removed the
if cv2.waitKey(20) == 27:
break
line, it worked much better than before too.
All of this sped up the project, and everything works fine now

Related

How to close OpenCV window (Python 3) in macOS?

I am first time using macOS High Sierra and Spider IDE for Python Programming.
The window does not close when I press q key on the keyboard. The output window freezes with the last frame and control returns to the Python prompt.
Any solution or workaround will be much appreciated. I would also love to know the reason.
Following are the details of versions of Python and OpenCV.
Python 3.9.7
OpenCV 4.5.3
Spyder 5import cv2
The code is as follows,
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)
window_name = "Result"
cv2.namedWindow(window_name)
while cap.isOpened():
success, img = cap.read()
if success:
cv2.imshow(window_name, img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyWindow(window_name)
notice: success variable - is a boolean flag that tells you if the next frame is available to read.
if success is false, you probably reached the end of the video. Then, your program will be stuck in infinite loop because you never meet the conditions of if success: ... so you cant reach the command if cv2.waitKey(1) & 0xFF == ord('q'): break.
so first thing, you have to change the conditions in your while loop.
change
while cap.isOpened():
success, img = cap.read()
if success:
cv2.imshow(window_name, img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
to
while cap.isOpened():
success, img = cap.read()
if not success:
break
cv2.imshow(window_name, img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
If you still have the same problem, as I had with my Jupyter Notebook, try to add cv2.waitKey(1) after destroying the window.
cv2.destroyAllWindows()
cv2.waitKey(1)
cap.release()

How to use cv2.waitKey(1) in Python OpenCV

I am doing some OpenCV python code and I have below code at the end:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
So whenever I press q, the code breaks which is working fine. But below code is not working:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if cv2.waitKey(1) & 0xFF == ord('a'):
print('a')
In above code, only q is working but if I press a, it is not printing a. Why is this not working. Can anyone please suggest me what is wrong here. Thanks
CODE:
cam = cv2.VideoCapture(0)
while True:
ret_val, image = cam.read()
cv2.imshow('my webcam', image)
if cv2.waitKey(1) & 0xFF == ord('a'):
print("a")
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
waitKey returns the ASCII value of key that's pressed while ord converts a character into its ASCII value. So something like this will work
key = cv2.waitKey(1)
if key == ord('q') :
break
elif key == ord('a'):
print('a')

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

cv2.waitKey returns 255 for all keys

I am trying to read the key value using cv2.waitKey(0) but it doesn't work. It waits forever. I used cv2.waitKey(1) to check what it returns and it was always 255 no matter which key I pressed.
while True:
key = cv2.waitKey(0)
print(key)
The above code does nothing, no matter whichever key I press.
while True:
key = cv2.waitKey(1) & 0xFF
print(key)
if key == ord('q'):
break
keeps printing 255 and doesn't break if I press 'q'.
I figured out the solution.
Looks like it requires a named window to be open for it to read the key values. So I tried the following and it worked.
cap = cv2.VideoCapture(0)
cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
key=cv2.waitKey(0) & 0xFF
print(key)
if key == ord('q'):
break
cv2.destroyAllWindows()

ocv.destroyWindow(name) don't close capture screen from second window

i used to display a usb camera capture from a second window (not main) and the window opened with ocv.imshow is not closed with ocv.destroywindow(name).
Here is the code which works from the main window :
cap = ocv.VideoCapture(0)
if(cap.isOpened()):
while(cap.isOpened()):
# Capture frame-by-frame
ret, the_frame = cap.read()
if ret==True:
ocv.imshow('frame',the_frame)
if ocv.waitKey(10) & 0xFF == ord('q'): #if (ocv.waitKey(5) != -1):
cap.release()
ocv.destroyWindow('frame') #destroyAllWindows()#
break
else:
print("No Usb Cam.")
Thanks for help,

Resources