I made a Python program that records the screen. But here’s what makes it different --- it doesn’t record the entire screen. Instead, it only captures the area around the mouse.
How It Works
The program uses cv2 (OpenCV) to track the mouse’s movement and some other libraries to handle the screen recording. Wherever the mouse goes, the recorder follows, capturing a specific region around it.
What’s the Catch?
When the mouse moves to the edges or corners of the screen, I had to handle it differently. Without adjustments, the recorder would try to capture an area beyond the screen boundary, leaving parts of the video black. To fix this, I added some math:
- If the mouse is near a corner or edge, the recording area shifts in the opposite direction.
- This keeps the recording clean and avoids showing any black screens.
Why Did I Make This?
Honestly, I was curious about combining screen recording with mouse tracking. Most screen recorders just capture the full display or a fixed window, but I wanted something more focused.
Personal Code Example
Here’s a snippet of the core logic I used to track the mouse and adjust the recording area dynamically:
import cv2
import numpy as np
from pynput.mouse import Listener
import pyautogui\
Screen resolution\
screen_width, screen_height = pyautogui.size()\
Define the size of the recording area around the mouse\
area_size = 200\
Function to get the mouse position\
def get_mouse_position():
mouse_x, mouse_y = pyautogui.position()
# Ensure the area stays within screen bounds\
x_start = max(0, mouse_x - area_size // 2)\
y_start = max(0, mouse_y - area_size // 2)
# Adjust if near the screen's edge\
if x_start + area_size > screen_width:\
x_start = screen_width - area_size\
if y_start + area_size > screen_height:\
y_start = screen_height - area_size
return x_start, y_start\
Start recording loop\
while True:
x_start, y_start = get_mouse_position()
# Capture the screen area around the mouse\
screenshot = pyautogui.screenshot(region=(x_start, y_start, area_size, area_size))\
screenshot_np = np.array(screenshot)\
screenshot_cv = cv2.cvtColor(screenshot_np, cv2.COLOR_RGB2BGR)
# Display the recording area\
cv2.imshow("Recording", screenshot_cv)
if cv2.waitKey(1) & 0xFF == ord('q'):\
break\
cv2.destroyAllWindows()
Current State
- It works well and follows the mouse smoothly.
- Edge cases (literally) are handled to avoid black regions when the mouse is near the screen’s boundary.
Not much else to say. It’s a simple project, but it was fun figuring out the math and making it all work together.