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

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.

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

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

Error using cv2 to train the camera (Python)

I am trying to train my camera using cv2 library. I am using a camera connected to Raspberry Pi3. it works fine since i tested the camera. However whenever I try to using the camera for face recognition later I keep getting this error:
return compile(source, filename, mode, PyCF_ONLY_AST)
IndentationError: expected an indented block
this is the code below:
import cv2
name = 'Mohammed' #replace with your name
cam = cv2.VideoCapture(0)
cv2.namedWindow("press space to take a photo", cv2.WINDOW_NORMAL)
cv2.resizeWindow("press space to take a photo", 500, 300)
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
cv2.imshow("press space to take a photo", frame)
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing…")
break
elif k%256 == 32:
# SPACE pressed
img_name = "dataset/"+ name +"/image_{}.jpg".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()

Using rewind in opencv

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

OpenCV input delay in capturing frames

I have written a code to enable capturing images from webcam feed using OpenCV. However there is an input delay whenever I press the key to capture my frame. There is no delay when I use it to quit, but there a significant delay when I use capture. I measured this by printing a statement inside both the cases, on pressing c the statement takes a delay before printing. The problem seems to me something like...the camera resources are being used and not freed up in time for the next key press or something like that....but not sure.
import cv2 as cv
import numpy as np
import glob
import matplotlib.pyplot as plt
cap = cv.VideoCapture(1)
img_counter = 0
while True:
ret, frame = cap.read()
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# cv.imshow('frame',frame)
cv.imshow('gray', gray)
if not ret:
break
if cv.waitKey(1) & 0xFF == ord('q'):
print('helloq')
break
elif cv.waitKey(1) & 0xFF == ord('c'):
print('hello{}'.format(img_counter))
img_name = "opencv_frame_{}.png".format(img_counter)
cv.imwrite(img_name, gray)
img_counter += 1
I am using an external web camera and
cv2.__version__ = 3.4.2`
Solved your issue, it seems like its caused by your key check.
You should not call waitKey(1) more than once. It causes lag.
Try this solution:
cap = cv.VideoCapture(0)
img_counter = 0
while True:
ret, frame = cap.read()
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# cv.imshow('frame',frame)
cv.imshow('gray', gray)
if not ret:
break
key = cv.waitKey(1)
if key==ord('c'):
print('img{}'.format(img_counter))
img_name = "opencv_frame_{}.png".format(img_counter)
cv.imwrite(img_name, gray)
img_counter += 1
print("Succesfully saved!")
if key==ord('q'):
print('Closing cam...')
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

Categories

Resources