In this blog, we will learn how to record any window using OpenCV-Python.
Installing Libraries:
- To install PIL and pywin32, write
1pip install pillow pywin32
in the cmd(See here). pywin32 will install win32gui, win32api, and win32con. - For installing winGuiAuto, download winGuiAuto.py from here. Save this as winGuiAuto.py in the python -> lib -> site-packages.
Steps:
- Create the window that you want to record (I used cv2.imshow() for that)
- Give the window name that you want to record in winGuiAuto.findTopWindow()
- Keep the window on top and set its position using win32gui.SetWindowPos()
- Get the coordinates of the window using win32gui.GetWindowPlacement()
- Grab an image of the area using ImageGrab.grab()
- Append all these images into a list.
- Create a VideoWriter object using cv2.VideoWriter()
- Convert each image color and save it.
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 41 |
import numpy as np import cv2 from PIL import ImageGrab import win32api import winGuiAuto import win32gui import win32con cap = cv2.VideoCapture(0) # Capture the window frame by frame image_list = [] for _ in range(70): ret, frame = cap.read() cv2.imshow('SCORE',frame) cv2.waitKey(1) hwnd = winGuiAuto.findTopWindow("SCORE") win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0,0,0,0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE) rect = win32gui.GetWindowPlacement(hwnd)[-1] image = ImageGrab.grab(rect) image_list.append(image) height,width,channel = np.array(image).shape cap.release() cv2.destroyAllWindows() out = cv2.VideoWriter('video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 5, (width,height)) for images in image_list: out.write(cv2.cvtColor(np.array(images),cv2.COLOR_BGR2RGB)) out.release() # Save into .gif #import imageio #image_gif = [] #for images in image_list: # print(np.array(images)) # image_gif.append(np.array(images)) #imageio.mimsave('movie.gif', image_gif,duration=0.2) |
If you want to make a .gif file, uncomment the last part.
Note: This works well for windows 8.1, but you might find some difficulty in capturing full window in windows 10.
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.