Как сделать скриншот в питоне
Как сделать скриншот с помощью скрипта Python в Linux
Я хочу сделать снимок экрана с помощью скрипта python и сохранить его. Меня интересует только решение для Linux, и я должен поддерживать любую среду на основе любой системы.
Ответ 1
Это работает без использования scrot или ImageMagick.
print «Размер окнаs %d на %d» % sz
print «Скриншот был сохранен как screenshot.png.»
print «Не удалось получить скриншот.»
Ответ 2
Created by Alex Snet on 2011-10-10.
Copyright (c) 2011 CodeTeam. All rights reserved.
from PyQt4.QtGui import QPixmap, QApplication
from PyQt4.Qt import QBuffer, QIODevice
wx.App() # Need to create an App instance before doing anything
bmp = wx.EmptyBitmap(size[0], size[1])
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
myWxImage = wx.ImageFromBitmap( myBitmap )
PilImage = Image.new( ‘RGB’, (myWxImage.GetWidth(), myWxImage.GetHeight()) )
if __name__ == ‘__main__’:
Ответ 3
from Xlib import display, X
raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
image = Image.fromstring(«RGB», (W, H), raw.data, «raw», «BGRX»)
Можно попробовать добавить некоторые типы в файлы-узкие места в PyXlib, а затем скомпилировать их с помощью Cython. Это может немного увеличить скорость.
Можно написать ядро функции на C, а затем использовать ее в python из ctypes, вот что можно сделать вместе:
void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) <
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);
unsigned long red_mask = image->red_mask;
unsigned long green_mask = image->green_mask;
unsigned long blue_mask = image->blue_mask;
unsigned long pixel = XGetPixel(image,x,y);
unsigned char blue = (pixel & blue_mask);
unsigned char green = (pixel & green_mask) >> 8;
unsigned char red = (pixel & red_mask) >> 16;
И затем python-файл:
from PIL import Image
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
objlength = size * 3
grab.getScreen(x1,y1, w, h, result)
return Image.frombuffer(‘RGB’, (w, h), result, ‘raw’, ‘RGB’, 0, 1)
if __name__ == ‘__main__’:
Крос сп латформенное решение с использованием wxPython :
wx.App() # Необходимо создать экземпляр приложения, прежде чем что-либо делать
bmp = wx.EmptyBitmap(size[0], size[1])
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
Как сделать скриншот в питоне
Скриншоты python
Всем привет. Сегодня мы рассмотрим как делать скриншоты в python используя модуль pyautogui. Поехали!
Для начала подключаем модуль pyautogui.
И теперь для того чтобы сделать скриншот, достаточно воспользоваться методом screenshot() который предоставляет нам данный модуль.
В результате выполнения данного кода мы сделаем скриншот всего экрана. Сам скриншот сохранится в виде изображения с названием screenshot и в формате png. Которые мы указали в самом методе screenshot(). Найти изображение вы сможете рядом с файлом программы. На выходе метод screenshot() возвращает объект изображения.
Если мы хотим сделать скриншот определенной части экрана. Можно воспользоваться свойством region.
Здесь в свойстве region мы указали что у нас будет снят левый верхний угол размером 300×400 пикселей. То есть первые две координаты(0,0) отвечают за левый верхний угол, а вторые(300, 400) за размер области экрана.
Вот мы у научились делать скриншоты в python. Помимо этого модуль pyautogui предоставляет нам возможность нахождения кусочков изображения в области где мы осуществляем скриншот.
Допустим у меня есть такой кусочек изображения.
Кто не знает это значок браузера mozilla firefox.
И теперь я хочу на своем рабочем столе найти координаты нахождения данного значка.
Для этого я использую метод locateOnScreen() и в качестве аргумента передаю ему изображение со значком.
В результате работы данный метод возвращает координаты где было найдено соответствие с изображением значка в области всего экрана.
Если я к примеру удалю ярлык браузера mozilla firefox из области экрана. Следовательно соответствия метод locateOnScreen() уже не найдет и нам вернется значение None.
Вот так с помощью метода locateOnScreen() вы можете в области экрана искать соответствия по картинке шаблону.
На этом у меня все. Надеюсь данная статья была для вас полезна. Если остались вопросы пишите их в комментариях к данной статье или группе в
А я с вами прощаюсь. Желаю успехов и удачи! Пока.
Оцените статью:
Статьи
Комментарии
Внимание. Комментарий теперь перед публикацией проходит модерацию
Все комментарии отправлены на модерацию
Запись экрана
Данное расширение позволяет записывать экран и выводит видео в формате webm
How to Get a Window or Fullscreen Screenshot in Python 3k? (without PIL)
With python 3, I’d like to get a handle to another window (not part of my application) such that I can either:
a) directly capture that window as a screenshot or
b) determine its position and size and capture it some other way
In case it is important, I am using Windows XP (edit: works in Windows 7 also).
I found this solution, but it is not quite what I need since it is full screen and more importantly, PIL to the best of my knowledge does not support 3.x yet.
4 Answers 4
Here’s how you can do it using PIL on win32. Given a window handle ( hwnd ), you should only need the last 4 lines of code. The preceding simply search for a window with «firefox» in the title. Since PIL’s source is available, you should be able to poke around the ImageGrab.grab(bbox) method and figure out the win32 code you need to make this happen.
Ars gave me all the pieces. I am just putting the pieces together here for anyone else who needs to get a screenshot in python 3.x. Next I need to figure out how to work with a win32 bitmap without having PIL to lean on.
Get a Screenshot (pass hwnd for a window instead of full screen):
Get a Window Handle by title (to pass to the above function):
This will take a new opened window and make a screenshot of it and then crop it with PIL also possible to find your specific window with pygetwindow.getAllTitles() and then fill in your window name in z3 to get screenshot of only that window.
If you definitely not want to use PIL you can maximize window with pygetwindow module and then make a screenshot with pyautogui module.
Note: not tested on Windows XP (but tested on Windows 10)
Screenshot FunctionsВ¶
PyAutoGUI can take screenshots, save them to files, and locate images within the screen. This is useful if you have a small image of, say, a button that needs to be clicked and want to locate it on the screen. These features are provided by the PyScreeze module, which is installed with PyAutoGUI.
Special Notes About UbuntuВ¶
Unfortunately, Ubuntu seems to have several deficiencies with installing Pillow. PNG and JPEG support are not included with Pillow out of the box on Ubuntu. The following links have more information: https://stackoverflow.com/questions/7648200/pip-install-pil-e-tickets-1-no-jpeg-png-support http://ubuntuforums.org/showthread.php?t=1751455
The screenshot() FunctionВ¶
Calling screenshot() will return an Image object (see the Pillow or PIL module documentation for details). Passing a string of a filename will save the screenshot to a file as well as return it as an Image object.
There is also an optional region keyword argument, if you do not want a screenshot of the entire screen. You can pass a four-integer tuple of the left, top, width, and height of the region to capture:
The Locate FunctionsВ¶
You can visually locate something on the screen if you have an image file of it. For example, say the calculator app was running on your computer and looked like this:
You can’t call the moveTo() and click() functions if you don’t know the exact screen coordinates of where the calculator buttons are. The calculator can appear in a slightly different place each time it is launched, causing you to re-find the coordinates each time. However, if you have an image of the button, such as the image of the 7 button:
The optional confidence keyword argument specifies the accuracy with which the function should locate the image on screen. This is helpful in case the function is not able to locate an image due to negligible pixel differences:
Note: You need to have OpenCV installed for the confidence keyword to work.
The locateCenterOnScreen() function combines locateOnScreen() and center() :
On a 1920 x 1080 screen, the locate function calls take about 1 or 2 seconds. This may be too slow for action video games, but works for most purposes and applications.
There are several В«locateВ» functions. They all start looking at the top-left corner of the screen (or image) and look to the right and then down. The arguments can either be a
The В«locate allВ» functions can be used in for loops or passed to list() :
These В«locateВ» functions are fairly expensive; they can take a full second to run. The best way to speed them up is to pass a region argument (a 4-integer tuple of (left, top, width, height)) to only search a smaller region of the screen instead of the full screen:
Grayscale MatchingВ¶
Optionally, you can pass grayscale=True to the locate functions to give a slight speedup (about 30%-ish). This desaturates the color from the images and screenshots, speeding up the locating but potentially causing false-positive matches.
Pixel MatchingВ¶
To obtain the RGB color of a pixel in a screenshot, use the Image object’s getpixel() method:
Or as a single function, call the pixel() PyAutoGUI function, which is a wrapper for the previous calls:
If you just need to verify that a single pixel matches a given pixel, call the pixelMatchesColor() function, passing it the X coordinate, Y coordinate, and RGB tuple of the color it represents:
The optional tolerance keyword argument specifies how much each of the red, green, and blue values can vary while still matching:
Захват изображения экрана с помощью Python с примерами
Хотя стандартная библиотека Python не предоставляет никакого метода для захвата экрана, мы можем сделать это с помощью нескольких сторонних модулей.
Вариант 1
Первый из них – PyAutoGUI, кроссплатформенный модуль для автоматизации задач. Мы можем захватить экран с помощью трех строк кода.
PyAutoGUI внутренне использует Pillow, одну из самых популярных библиотек для работы с изображениями, поэтому screenshot является экземпляром PIL.Image.Image.
Чтобы захватить только часть экрана, мы используем параметр region – кортеж со структурой (X, Y, Width, Height).
Самый простой способ установить модуль и все его зависимости – через pip.
Для корректной работы PyAutoGUI в Linux необходимо также установить следующие зависимости.
В Max OS требуется следующее:
В Windows пакет не требует дополнительной установки.
Вариант 2
Еще один пакет, похожий на PyAutoGUI – AutoPy, инструментарий автоматизации платформы, написанный на C.
Его API гораздо более элегантно, проще и приятнее, чем у предыдущего модуля, но на данный момент он поддерживает только Python 2 (именно поэтому он является вариантом номер два).
Захват экрана так же прост:
Функция capture_screen может принимать заданную область экрана в виде структуры ((X, Y), (Width, Height)).
Установить можно также через pip.
Вариант 3
pyscreenshot – это модуль, созданный специально для выполнения этой задачи, доступный для Python 2 и 3.
Его единственная зависимость – PIL/Pillow.
В Linux также требуется один из следующих пакетов: scrot, ImageMagick, PyGTK, PyQt или wxPython.
В Mac OS X для этого требуется Quartz или screencapture.
Функция всегда возвращает экземпляр PIL.Image.Image.
Можно также захватить только часть экрана.
Обратите внимание, что структура bbox имеет вид (X1, Y1, X2, Y2).