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: object

Multiple 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, and with_cursor keyword arguments.

Added in version 10.2.0: backend keyword 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: monitor can be a tuple like the one PIL.ImageGrab.grab() accepts: (left, top, right, bottom)

Parameters:

monitor – The coordinates and size of the box to capture. See monitors for 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._monitors with all information and use it as a cache:

  • self._monitors[0] is a dict of all monitors together

  • self._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 corner

  • top: the y-coordinate of the upper-left corner

  • width: the width

  • height: the height

  • is_primary: (optional) true if this is the primary monitor

  • name: (optional) human-readable device name

  • unique_id: (optional) platform-specific stable identifier for the monitor

  • output: (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). -1 grabs all monitors, 0 grabs each monitor, and N grabs monitor N.

  • output (str ) – The output filename. Keywords: {mon}, {top}, {left}, {width}, {height}, {date}.

  • callback (Callable ) – Called before saving the screenshot; receives the output argument.

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.

property max_displays: int #

Maximum number of displays to handle.

Availability: macOS

Added in version 8.0.0.

property with_cursor: bool #

Include the mouse cursor in screenshots.

In some circumstances, it may not be possible to include the cursor. In that case, MSS will automatically change this to False when the object is created.

This cannot be changed after creating the object.

Added in version 8.0.0.

class mss.ScreenShot(data: Buffer, monitor: Monitor, /, *, size: Size | None = None)#

Bases: object

Screenshot object.

Note

A better name would have been Image, but to prevent collisions with PIL.Image, it has been decided to use ScreenShot.

pos: Pos#

NamedTuple of the screenshot coordinates.

size: Size#

NamedTuple of the screenshot size.

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 bytes object. It was changed to a memoryview for improved performance. Most practical uses are unaffected by this change, as memoryview supports most of the same operations as bytes. If needed, you can use memoryview.tobytes() to get a bytes object.

property raw: memoryview [int ]#

Deprecated alias for bgra.

Deprecated since version 10.2.0: Use bgra instead. This alias will be removed in a future version.

Changed in version 11.0.0: Prior to this version, this was a bytearray . This raw alias is retained, although as a memoryview , for backwards compatibility: most existing uses are not affected, as memoryview supports most of the same operations as bytearray. If needed, you can use bytearray(raw) to get a bytearray object.

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 bgra property directly is usually more efficient.

Changed in version 11.0.0: Prior to this version, this was a bytes object. It was changed to a memoryview for improved performance. Most practical uses are unaffected by this change, as memoryview supports most of the same operations as bytes. If needed, you can use memoryview.tobytes() to get a bytes object.

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, and channels="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 usually torch.float32; see torch.get_default_dtype() .

  • device – The requested destination device, as a torch.device or string. Default is the current default PyTorch device; see torch.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 in to_numpy() or to_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:
  • 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 dtype. Can be a string like "float32" (default), a tf.DType , or a np.dtype .

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.

property top: int #

Convenient accessor to the top position.

property left: int #

Convenient accessor to the left position.

property width: int #

Convenient accessor to the width size.

property height: int #

Convenient accessor to the height size.

exception mss.ScreenShotError(message: str , /, *, details: dict [str , Any ] | None = None)#

Bases: Exception

Error 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.

mss.mss(**kwargs: Any ) MSS#

Create an mss.MSS instance for the current platform.

Deprecated since version 10.2.0: Use mss.MSS directly.

Data Models#

class mss.models.Pos(left, top)#

Bases: NamedTuple

left: int #

The horizontal X coordinate of the position.

top: int #

The vertical Y coordinate of the position.

class mss.models.Size(width, height)#

Bases: NamedTuple

width: int #

The horizontal X width.

height: int #

The vertical Y height.