Most of you must have clicked the photograph with a Timer. This feature sets a countdown before clicking a photograph. In this tutorial, we will be doing the same i.e. creating our own camera timer using OpenCV-Python. Sounds interesting, so let’s get started.
The main idea is that whenever a particular key is pressed (Here, I have used ‘q’), the countdown will begin and a photo will be clicked and saved at the desired location.
Here, we will be using cv2.putText() function for drawing the countdown on the video. This function has the following arguments
1 |
cv2.putText(img, text, position, font, fontScale, color, thickness, lineType, bottomLeftOrigin) |
This function draws the text on the input image at the specified position. If the specified font is unable to render any character, it is replaced by a question mark.
Now let’s see how to do this
Steps:
- Open the camera using cv2.VideoCapture()
- Until the camera is open
- Read the frame and display it using cv2.imshow()
- Set the countdown. Here, I have taken this as 30 and I am displaying it after 10 frames so that it is easily visible. Otherwise, it will be too fast. You can set it to anything as you wish
- Set a key for the countdown to begin
- If the key is pressed, show the countdown on the video using cv2.putText(). As the countdown finishes, save the frame at the desired location.
- Otherwise, the video will continue streaming
- On pressing ‘Esc’ the video will stop streaming.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import cv2 import time # Open the camera cap = cv2.VideoCapture(0) while True: # Read and display each frame ret, img = cap.read() cv2.imshow('a',img) k = cv2.waitKey(125) # Specify the countdown j = 30 # set the key for the countdown to begin if k == ord('q'): while j>=10: ret, img = cap.read() # Display the countdown after 10 frames so that it is easily visible otherwise, # it will be fast. You can set it to anything or remove this condition and put # countdown on each frame if j%10 == 0: # specify the font and draw the countdown using puttext font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,str(j//10),(250,250), font, 7,(255,255,255),10,cv2.LINE_AA) cv2.imshow('a',img) cv2.waitKey(125) j = j-1 else: ret, img = cap.read() # Display the clicked frame for 1 sec. # You can increase time in waitKey also cv2.imshow('a',img) cv2.waitKey(1000) # Save the frame cv2.imwrite('D:/downloads/camera.jpg',img) # Press Esc to exit elif k == 27: break cap.release() cv2.destroyAllWindows() |
The output looks like this
Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.