MSS API#
Core Package#
An ultra fast cross-platform multiple screenshots module in pure python using ctypes.
- class mss.MSS(*, backend: str = 'default', compression_level: int = 6, with_cursor: bool | _PlatformSpecific = False, display: bytes | str | None | _PlatformSpecific = None, max_displays: int | _PlatformSpecific = 32)#
Bases:
objectMultiple ScreenShots class
- Parameters:
backend – Backend selector, for platforms with multiple backends.
compression_level – PNG compression level.
with_cursor – Include the mouse cursor in screenshots. Optional, default False. (GNU/Linux only)
display – X11 display name. Optional; default
$DISPLAY. (GNU/Linux only)max_displays – Maximum number of displays to enumerate. Optional, default 32. (macOS only).
Added in version 8.0.0:
compression_level,display,max_displays, andwith_cursorkeyword arguments.Added in version 10.2.0:
backendkeyword argument.- compression_level#
PNG compression level used when saving the screenshot data into a file (see
zlib.compress()for details).Added in version 3.2.0.
- close() None #
Clean up.
This releases resources that MSS may be using. Once the MSS object is closed, it may not be used again.
It is safe to call this multiple times; multiple calls have no effect.
Rather than use
close()explicitly, we recommend you use the MSS object as a context manager:with mss.MSS() as sct: ...
- grab(monitor: Monitor | tuple [int , int , int , int ], /) ScreenShot#
Retrieve screen pixels for a given monitor.
Note:
monitorcan be a tuple like the onePIL.ImageGrab.grab()accepts:(left, top, right, bottom)- Parameters:
monitor – The coordinates and size of the box to capture. See
monitorsfor object details.- Returns:
Screenshot of the requested region.
- property monitors: Monitors#
Get positions of all monitors. If the monitor has rotation, you have to deal with it inside this method.
This method has to fill
self._monitorswith all information and use it as a cache:self._monitors[0]is a dict of all monitors togetherself._monitors[N]is a dict of the monitor N (with N > 0)
Each monitor is a dict with:
left: the x-coordinate of the upper-left cornertop: the y-coordinate of the upper-left cornerwidth: the widthheight: the heightis_primary: (optional) true if this is the primary monitorname: (optional) human-readable device nameunique_id: (optional) platform-specific stable identifier for the monitoroutput: (optional, Linux only) monitor output name, compatible with xrandr
- property primary_monitor: Monitor#
Get the primary monitor.
Returns the monitor marked as primary. If no monitor is marked as primary (or the platform doesn’t support primary monitor detection), returns the first monitor (at index 1).
- Raises:
ScreenShotError – If no monitors are available.
Added in version 10.2.0.
- save(*, mon: int = 0, output: str = 'monitor-{mon}.png', callback: Callable[[str ], None ] | None = None) Iterator[str ]#
Grab a screenshot and save it to a file.
- Parameters:
mon (int ) – The monitor to screenshot (default=0).
-1grabs all monitors,0grabs each monitor, andNgrabs monitorN.output (str ) – The output filename. Keywords:
{mon},{top},{left},{width},{height},{date}.callback (Callable ) – Called before saving the screenshot; receives the
outputargument.
- Returns:
Created file(s).
- shot(**kwargs: Any ) str #
Helper to save the screenshot of the 1st monitor, by default. You can pass the same arguments as for
save().
- property performance_status: list [str ]#
Implementation-specific notes that might affect performance.
For instance, on GNU/Linux, when using the default XShmGetImage backend, this will include a note if the MIT-SHM extension is not usable.
This may not be ready until one screenshot has been taken.
This is meant only for debugging purposes; the contents are subject to change at any time.
Added in version 10.2.0.
- class mss.ScreenShot(data: Buffer, monitor: Monitor, /, *, size: Size | None = None)#
Bases:
objectScreenshot object.
Note
A better name would have been Image, but to prevent collisions with PIL.Image, it has been decided to use ScreenShot.
- classmethod from_size(data: Buffer, width: int , height: int , /) ScreenShot#
Instantiate a new class given only screenshot’s data and size.
- property bgra: memoryview [int ]#
BGRx values from the BGRx raw pixels.
The format is a memoryview object of bytes. These are in a BGRxBGRx… sequence. A specific pixel can be accessed as
bgra[(y * width + x) * 4:(y * width + x) * 4 + 4].Note
While the name is
bgra, the alpha channel may or may not be valid.Changed in version 11.0.0: Prior to this version, this was a
bytesobject. It was changed to a memoryview for improved performance. Most practical uses are unaffected by this change, asmemoryviewsupports most of the same operations asbytes. If needed, you can usememoryview.tobytes()to get abytesobject.
- property raw: memoryview [int ]#
Deprecated alias for
bgra.Deprecated since version 10.2.0: Use
bgrainstead. This alias will be removed in a future version.Changed in version 11.0.0: Prior to this version, this was a
bytearray. Thisrawalias is retained, although as amemoryview, for backwards compatibility: most existing uses are not affected, asmemoryviewsupports most of the same operations asbytearray. If needed, you can usebytearray(raw)to get abytearrayobject.
- property pixels: list [tuple [tuple [int , int , int ], ...]]#
RGB tuples.
The format is a list of rows. Each row is a list of pixels. Each pixel is a tuple of (R, G, B).
- pixel(coord_x: int , coord_y: int ) tuple [int , int , int ]#
Return the pixel value at a given position.
- Returns:
A tuple of (R, G, B) values.
- property rgb: memoryview #
Compute RGB values from the BGRA raw pixels.
The format is a memoryview object of bytes. These are in a RGBRGB… sequence. A specific pixel can be accessed as
rgb[(y * width + x) * 3:(y * width + x) * 3 + 3].Note
This is a computed property. If possible, using the
bgraproperty directly is usually more efficient.Changed in version 11.0.0: Prior to this version, this was a
bytesobject. It was changed to a memoryview for improved performance. Most practical uses are unaffected by this change, asmemoryviewsupports most of the same operations asbytes. If needed, you can usememoryview.tobytes()to get abytesobject.
- to_pil(mode: str = 'RGB') PIL.Image.Image #
Convert the screenshot to a Pillow image.
- Parameters:
mode – The requested image mode. Must be
"RGB"(default) or"RGBA".
When requesting
"RGBA", the alpha channel may not represent meaningful transparency on all platforms/backends.Added in version 11.0.0.
- to_numpy(channels: Channels = 'RGB', layout: Layout = 'HWC', dtype: numpy.dtype | type | None = None) numpy.ndarray #
Convert the screenshot to a NumPy array.
- Parameters:
channels – The requested channel order. Must be
"BGRA","BGR","RGB"(default), or"RGBA".layout – The requested layout. Must be
"HWC"(default) or"CHW".dtype – The requested data type. The default is
np.uint8.
Floating point dtypes are scaled to the
[0, 1]range.Use
channels="BGR"for OpenCV, andchannels="RGB"(the default) for scikit-image and most other frameworks.When requesting
"RGBA"or"BGRA", the alpha channel may not represent meaningful transparency on all platforms/backends.Added in version 11.0.0.
- to_torch(channels: Channels = 'RGB', layout: Layout = 'CHW', dtype: torch.dtype | None = None, device: torch.device | str | None = None) torch.Tensor #
Convert the screenshot to a PyTorch tensor.
- Parameters:
channels – The requested channel order. Must be
"BGRA","BGR","RGB"(default), or"RGBA".layout – The requested layout. Must be
"CHW"(default) or"HWC".dtype – The requested dtype as a
torch.dtype. Defaults to the current PyTorch default dtype, which is usuallytorch.float32; seetorch.get_default_dtype().device – The requested destination device, as a
torch.deviceor string. Default is the current default PyTorch device; seetorch.get_default_device().
Floating point dtypes are scaled to the
[0, 1]range.The default layout is
"CHW"because it is more commonly used in PyTorch models. This is different than into_numpy()orto_tensorflow(), which default to"HWC".When requesting
"RGBA"or"BGRA", the alpha channel may not represent meaningful transparency on all platforms/backends.Added in version 11.0.0.
- to_tensorflow(channels: Channels = 'RGB', layout: Layout = 'HWC', dtype: tf.dtypes.DType | numpy.dtype | str = 'float32') tf.Tensor #
Convert the screenshot to a TensorFlow tensor.
- Parameters:
Device and stream management is handled by TensorFlow.
Floating point dtypes are scaled to the
[0, 1]range.When requesting
"RGBA"or"BGRA", the alpha channel may not represent meaningful transparency on all platforms/backends.Added in version 11.0.0.
- exception mss.ScreenShotError(message: str , /, *, details: dict [str , Any ] | None = None)#
Bases:
ExceptionError handling class.
- details#
On GNU/Linux, and if the error comes from the XServer, it contains XError details. This is an empty dict by default.
For XErrors, you can find information on Using the Default Error Handlers .
Added in version 3.3.0.
Data Models#
- class mss.models.Pos(left, top)#
Bases:
NamedTuple