This records a 5-second screencast of a 300x300px top-left square of the screen (10 frame per second):
import time, numpy as np, pyautogui, imageio
t0 = time.time()
with imageio.get_writer('test.gif', mode='I', duration=0.1) as writer:
while True:
t1 = time.time()
img = pyautogui.screenshot(region=(0,0,300,300))
writer.append_data(np.array(img))
t2 = time.time()
time.sleep(0.1 - (t2 - t1))
if t2 - t0 > 5:
break
It works, but the output file is very big (1.5 MB for 5 seconds and only 300x300px!). Some programs (such as ScreenToGif freeware) are able to produce optimized GIF by detecting unmodified pixels in consecutive frames, and then it would maybe take 50 KB instead of 1.5 MB for the same file.
How to produce such an optimized GIF with Python? Is it possible with imageio
; if not, is there a way to do it manually?