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 | _PlatformSpecific | None = 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(region: Monitor | Region | dict[str, Any] | tuple[int, int, int, int], /) ScreenShot#
Retrieve screen pixels for a given region.
regioncan be amss.models.Monitor, amss.models.Region, a region dictionary, or a tuple like the onePIL.ImageGrab.grab()accepts:(left, top, right, bottom).- Parameters:
region – The coordinates and size of the box to capture.
- Returns:
Screenshot of the requested region.
- property monitors: Monitors#
Get positions of all monitors.
If a monitor is rotated, its dimensions reflect its displayed orientation. In other words, height is the visible height, not the number of scanout lines.
The first element,
monitors[0], is all the monitors together. It is the virtual desktop, holding all the monitors. The remaining elements,monitors[N](with N > 0), are the individual displays.If monitors are being mirrored, the list will only include one of the mirrored copies.
See also
- 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) Sequence[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},{is_primary},{name},{unique_id},{output},{date}. Optional metadata is formatted asNonewhen unavailable.callback (Callable) – Called before saving the screenshot; receives the
outputargument.
- Returns:
Names of created file(s).
Changed in version 11.0.0: Prior to this version an Iterator was returned, rather than a Sequence.
- 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, region: Monitor | Region | dict[str, Any], /, *, 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.Region(left: int, top: int, width: int, height: int)#
Bases:
objectRectangular screen region.
- class mss.models.Monitor(left: int, top: int, width: int, height: int, name: str | None = None, is_primary: bool | None = None, unique_id: str | None = None, output: str | None = None)#
Bases:
objectMonitor geometry and optional platform metadata.
See also
Changed in version 11.0.0: Prior to this version,
Monitorwas an alias fordict[str, int]. In MSS 11, it is still possible to access attributes with dict-style string-key access, such asmonitor["left"], but this behavior is deprecated and will be removed in a later version.- name: str | None#
The human-readable name of this monitor, typically the brand and model.
Added in version 10.2.0.
- is_primary: bool | None#
Whether this is the primary monitor, according to the operating system. If MSS can’t determine the primary monitor, this will be
Nonefor all monitors, althoughMSS.primary_monitorwill still return a monitor (the first one).Added in version 10.2.0.
- unique_id: str | None#
The platform-specific stable identifier. This is generally stable across reboots, or ordinary disconnection / reconnection, but may change when the display hardware or connection topology changes.
Added in version 10.2.0.
- class mss.models.Pos(left, top)#
Bases:
NamedTuple