Search code examples
linuxpython-3.xperformanceimagemagickscreenshot

Imagemagick's import is frustratingly slow


I am writing an small python script to take screenshots of a game window (which will be in the background/minimized) and performing some simple template matching and ocr using cv2. I am currently calling im's import as follows:

import -window windowID png:-

to take a screenshot of an inactive window.

However this takes almost 4s and is easily the slowest part of my script by a factor of 100x.

Is there any alternative to import or perhaps another way of approaching this that will be faster?

I have already tried graphicsmagick (ended up being slower than imagemagick) and xwd (did not capture the unfocused window even though the windowID was specified)

Link to full python script (Line 44 is where the screenshot taking happens)


Solution

  • You are doing all the PNG encoding and zlib compression in ImageMagick and then decompressing it all again in OpenCV. I guess you would do better if you found a format that is more closely shared between the two.

    Specifically, ImageMagick could give you RGB pixels directly, which you could then convert to BGR very easily in OpenCV with cvtColor().

    import -window windowID rgb:
    

    You would have to query the window dimensions to get width and height.

    Alternatively, you could use PPM format which OpenCV can also read without any libraries and which includes dimensions:

    import -window windowID ppm: