4

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?

Basj
  • 41,386
  • 99
  • 383
  • 673
  • Just to give a perspective on how ScreenToGif works: It basically checks which pixels got a different color and mark the ones without changes with a color that will be treated later as the transparent mask. – Nicke Manarin Dec 03 '20 at 20:11

1 Answers1

0

You can use the mss module. It is faster. You could check the similar question here, hope the performance increases.

SHRIDU MANISH
  • 59
  • 1
  • 6
  • 1
    Thank you for your answer and welcome to SO! In order to make this answer useful for future reference, can you include code demonstrating how to use the module you mention? – Basj Dec 30 '20 at 14:43