A screensaver is a computer program that fills the screen with anything you wish when the computer is left idle for some time. Most of you might have used a screensaver on your laptops, TV etc. In the good old days, they used to fascinate most of us. In this blog, we will be creating a bouncing ball screensaver using OpenCV-Python.
Task:
Create a Window that we can write text on. If we don’t write for 10 seconds screensaver will start.
For this we need to do two things:
- First, we need to check whether a key is pressed in the specified time. Here, I have used 10 sec.
- Second, c
reate a bouncing ball screensaver and display it only if no key is pressed in the specified time, otherwise, display the original screen.
The first part can be done using the OpenCV cv2.waitKey() function which waits for a specific time for a key press (See here for more details).
For the second part, we first need to create a bouncing ball screensaver. The main idea is to change the sign of increment (dx and dy in the code below) on collision with the boundaries. This can be done using the following 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 |
def screensaver(): img = np.zeros((480,640,3),dtype='uint8') dx,dy =1,1 x,y = 100,100 while True: # Display the image cv2.imshow('a',img) k = cv2.waitKey(10) img = np.zeros((480,640,3),dtype='uint8') # Increment the position x = x+dx y = y+dy cv2.circle(img,(x,y),20,(255,0,0),-1) if k != -1: break # Change the sign of increment on collision with the boundary if y >=480: dy *= -1 elif y<=0: dy *= -1 if x >=640: dx *= -1 elif x<=0: dx *= -1 cv2.destroyAllWindows() |
The snapshot of the screensaver looks like this
Now, we need to integrate this screensaver function with the cv2.waitKey() function as shown in the code below
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 |
import cv2 import numpy as np # Background Image img1 = cv2.imread('D:/downloads/original_image.png') # Initialize these for text placement i = 0 a,b = 30,30 while True: cv2.imshow('a',img1) k = cv2.waitKey(10000) # If no key is pressed, display the screensaver if k == -1: screensaver() # Press Escape to exit elif k == 27: break # Otherwise write real time text on the image. # This is used for visualization only # You can use anything here. else: font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img1,chr(k),(a+i,b), font, 0.5,(255,255,255),2,cv2.LINE_AA) if a+i >= img1.shape[1]: b = b+15 i = 0 i +=10 cv2.destroyAllWindows() |
You need to set the size of the screensaver and background image to be the same. 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.