2016년 10월 5일 수요일

Fast screen capture in python.

I need to screen capture to make simple macro program.

First, I use ImageGrab in pillow or pyscreenshot.
But, These are too slow for my program.

Then, I found good library-wx.
wx is GUI development library based on C++.
Capture method in wx is more faster than ImageGrab.

But, on pixel processing using pillow methods, PNG is on error.
I don't know why it is, BMP is ok.

Sample code in python.

import time
import pyscreenshot as ImageGrab
import wx
from PIL import Image


def main():
    count = 10
 
    start = time.time()
    for i in xrange(count):
        im = ImageGrab.grab(bbox=(0, 0, 100, 100))
        im.save('ImageGrab.png')
     
    print time.time() - start

    start = time.time()
    app = wx.App()
    screen = wx.ScreenDC()
    for i in xrange(count):
        bmp = wx.EmptyBitmap(100, 100)
        mem = wx.MemoryDC(bmp)
        mem.Blit(0, 0, 100, 100, screen, 0, 0)
        del mem
        bmp.SaveFile('wx.bmp', wx.BITMAP_TYPE_BMP)
     
    print time.time() - start


if __name__ == '__main__':
    main()


Get 0,0 to 100,100 screen image and save it 10 times.

Execute results.

17.631000042
0.203000068665

In my computer, wx is faster than pyscreenshot about 80 times.
If you need to fast screen capture, use wx.

wx install url:
https://wxpython.org/download.php

파이썬으로 바탕화면 빠르게 캡처 하기.

간단한 매크로 프로그램을 만드는 중,
바탕화면을 캡처해서 처리해야 하는 일이 필요했다.

 맨 처음에는 pillow 라이브러리에 있는 ImageGrab이나 pyscreenshot을 사용했다.
하지만, 내가 하고 싶은 일을 처리하는 시간보다, 바탕화면을 가져오는 데
더 많은 시간이 들어서 프로그램이 비효율적이였다.

 더 좋은 방법이 없나 찾아 보다가, wx를 알게 되었다.
원래 wx는 C++에서 시작된 GUI 프로그램 개발 라이브러리이다.
기능중에 바탕화면 정보를 가져오는 함수가 있어서 써 보니,
월등히 빠른 속도로 캡처를 해서 프로그램이 훨씬 빨라졌다.

 단, pillow 함수를 이용해서 wx가 캡처한 이미지를 픽셀 단위로 처리하려 할 때,
이미지 확장자명이 png면 오류가 발생했다. 이 문제의 원인은 잘 모르겠지만,
wx에서 이미지를 저장할 때 bmp으로 저장하면 에러가 발생하지 않는다.

아래는 참고 코드이다.

import time
import pyscreenshot as ImageGrab
import wx
from PIL import Image


def main():
    count = 10
 
    start = time.time()
    for i in xrange(count):
        im = ImageGrab.grab(bbox=(0, 0, 100, 100))
        im.save('ImageGrab.png')
     
    print time.time() - start

    start = time.time()
    app = wx.App()
    screen = wx.ScreenDC()
    for i in xrange(count):
        bmp = wx.EmptyBitmap(100, 100)
        mem = wx.MemoryDC(bmp)
        mem.Blit(0, 0, 100, 100, screen, 0, 0)
        del mem
        bmp.SaveFile('wx.bmp', wx.BITMAP_TYPE_BMP)
     
    print time.time() - start


if __name__ == '__main__':
    main()


각각 모니터에서 0, 0에서 100, 100 부분을 캡처한 뒤 파일로 저장하는 과정을
10번 반복한다.

아래는 실행 결과이다.

17.631000042
0.203000068665

내 컴퓨터 환경에서 wx 는 pyscreenshot 보다 대략 80배 정도 빠르다.
빠른 캡처가 필요하다면, wx를 사용하는게 좋을 것이다.

wx 설지 url:

https://wxpython.org/download.php