An ultra fast cross-platform multiple screenshots module in pure Python using ctypes.

Overview

Python MSS

https://travis-ci.org/BoboTiG/python-mss.svg?branch=master https://ci.appveyor.com/api/projects/status/72dik18r6b746mb0?svg=true https://pepy.tech/badge/mss
from mss import mss

# The simplest use, save a screen shot of the 1st monitor
with mss() as sct:
    sct.shot()

An ultra fast cross-platform multiple screenshots module in pure python using ctypes.

  • Python 3.5+ and PEP8 compliant, no dependency, thread-safe;
  • very basic, it will grab one screen shot by monitor or a screen shot of all monitors and save it to a PNG file;
  • but you can use PIL and benefit from all its formats (or add yours directly);
  • integrate well with Numpy and OpenCV;
  • it could be easily embedded into games and other software which require fast and platform optimized methods to grab screen shots (like AI, Computer Vision);
  • get the source code on GitHub;
  • learn with a bunch of examples;
  • you can report a bug;
  • need some help? Use the tag python-mss on StackOverflow;
  • and there is a complete, and beautiful, documentation :)
  • MSS stands for Multiple Screen Shots;

Installation

You can install it with pip:

python -m pip install -U --user mss

Or you can install it with conda:

conda install -c conda-forge python-mss
Comments
  • mss with PyQt5 crash in segmentation fault

    mss with PyQt5 crash in segmentation fault

    General OS information:

    RELEASE=18 CODENAME=sarah EDITION="Cinnamon 64-bit" DESCRIPTION="Linux Mint 18 Sarah" DESKTOP=Gnome TOOLKIT=GTK NEW_FEATURES_URL=http://www.linuxmint.com/rel_sarah_cinnamon_whatsnew.php RELEASE_NOTES_URL=http://www.linuxmint.com/rel_sarah_cinnamon.php USER_GUIDE_URL=help:linuxmint GRUB_TITLE=Linux Mint 18 Cinnamon 64-bit

    • Resolutions:
      • Monitor 1: 1920x1080
      • Monitor 2: 1920x1080
      • Monitor 3: 1920x1080 Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
    • MSS version: 4.0.0

    Description of the warning/error

    I have tried to use mss to make screenshots from console code with python. Works just fine. Now I have made a GUI with PyQt5 and it is working just fine in windows. But in Linux, I get a segmentation fault

    This is the smallest code that makes the error:

    from PyQt5 import QtWidgets
    from mss import mss
    
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
    
        with mss() as sct:
            pass
    

    I have made my code in PyCharm and I have realized that if I run the debugger without even any breakpoints, the code works. But if I RUN the code from within PyCharm it crashes with seg fault. The same thing if I run the program from a console.

    not a bug GNU/Linux 
    opened by RobotPsykolog 30
  • Bad multiple screen grab

    Bad multiple screen grab

    I'm working on 10.12.1 MacOS Sierra with 2.0.18 mss version and python 3.5. When today I tried to create multiple screenshots using mss according to documentation. And with two different screens with resolutions {'height': 1200, 'left': 0, 'top': 0, 'width': 1920}, {'height': 768, 'left': -1366, 'top': 0, 'width': 1366}. The bigger screenshot looks fine but the smaller gives a very bad result: http://imgur.com/a/hKrHw. What is the cause of it?

    bug macOS pending 
    opened by Archarachne 22
  • [Windows] MSS is not thread-safe

    [Windows] MSS is not thread-safe

    The problem

    Hello, I try to do stuff like this:

    • Http request from JS
    • Python handles it with Flask
    • When Python Flask gets a request it will grab a current display view (screenshot), resize it, convert to base64 and return it as response

    It's all ok, but when I send second http request - python mss fails.

    (there's .js and .py files because it could somehow help)

    server.py

    # Image processing, FPS in console
    import mss, cv2, base64, time
    import numpy as np
    from PIL import Image as i
    
    # Get current frame of second monitor
    def getFrame():
        start_time = time.perf_counter()
    
        # Get frame (only rgb - smaller size)
        frame_rgb     = mss.mss().grab(mss.mss().monitors[2]).rgb # type: bytes, len: 1280*720*3 (w, h, r, g, b)
    
        # Convert it from bytes to resize
        frame_image   = i.frombytes("RGB", (1280, 720), frame_rgb, "raw", "RGB") # PIL.Image.Image
        frame_array   = np.array(frame_image) # type: numpy.ndarray
        frame_resized = cv2.resize(frame_array, (640, 360), interpolation = cv2.INTER_CUBIC) # type: numpy.ndarray
    
        # Encode to base64 - prepared to send
        frame_base64  = base64.b64encode(frame_resized) # type: bytes, len: 640*360*4 (w, h, r, g, b, ???)
    
        print(f'{ round( 1 / (time.perf_counter() - start_time), 2) } fps')
        return frame_base64
    
    # Flask request handler
    from flask import Flask, request
    from flask_cors import CORS
    
    app = Flask(__name__)
    cors = CORS(app)
    
    @app.route('/frame_base64')
    def frame_base64():
        return getFrame()
    
    app.run(debug=True, port=7999)
    

    script.js (little weird because of compilation from coffeescript)

    (function() {
    
      $(document).ready(function() {
    
        return $.ajax({
          type: 'get',
          url: ' http://127.0.0.1:7999/frame_base64',
          success: (response) => {
            return console.log(response);
          }
        });
    
      });
    
    }).call(this);
    

    Full console log:

    D:\web\projects\html-display-stream\backend>python server.py
     * Serving Flask app "server" (lazy loading)
     * Environment: production
       WARNING: This is a development server. Do not use it in a production deployment.
       Use a production WSGI server instead.
     * Debug mode: on
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 258-577-249
     * Running on http://127.0.0.1:7999/ (Press CTRL+C to quit)
    18.0 fps
    127.0.0.1 - - [26/Feb/2020 00:36:05] "GET /frame_base64 HTTP/1.1" 200 -
    127.0.0.1 - - [26/Feb/2020 00:36:06] "GET /frame_base64 HTTP/1.1" 500 -
    Traceback (most recent call last):
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2463, in __call__
    
        return self.wsgi_app(environ, start_response)
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2449, in wsgi_app
    
        response = self.handle_exception(e)
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
        return cors_after_request(app.make_response(f(*args, **kwargs)))
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1866, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\_compat.py", line 39, in reraise
        raise value
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    
        response = self.full_dispatch_request()
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
        return cors_after_request(app.make_response(f(*args, **kwargs)))
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
        reraise(exc_type, exc_value, tb)
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\_compat.py", line 39, in reraise
        raise value
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
        rv = self.dispatch_request()
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1935, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "D:\web\projects\html-display-stream\backend\server.py", line 33, in frame_base64
        return getFrame()
      File "D:\web\projects\html-display-stream\backend\server.py", line 11, in getFrame
        frame_rgb     = mss.mss().grab(mss.mss().monitors[2]).rgb # type: bytes, len: 1280*720*3 (w, h, r, g, b)
      File "C:\Users\Roman\AppData\Local\Programs\Python\Python37\lib\site-packages\mss\windows.py", line 291, in grab
        raise ScreenShotError("gdi32.GetDIBits() failed.")
    mss.exception.ScreenShotError: gdi32.GetDIBits() failed.
    

    Additional info:

    Windows 7 x64 Service Pack 1 Monitors: 1920×1080, 1280×720 Python 3.7.6 pip 20.0.2 python-mss last version of now

    P.S.: Sorry for my bad English.

    Thanks

    bug Windows 
    opened by RamoFX 19
  • Content of mss().monitors does not correspond with screen resolution, cannot take screenshots

    Content of mss().monitors does not correspond with screen resolution, cannot take screenshots

    General informations:

    • OS name: macOS
    • OS version: 10.13.1 "High Sierra"
    • OS architecture: 64 bits
    • Monitor(s)'s resolution: 2880x1800, default system scaling/resolution
    • Result of the command python --version: Python 2.7.10, however python3 --version yields Python 3.6.2 (which is what was used.)

    Description of the warning/error

    The content of mss().monitors is incorrect:

    from mss import mss
    mss().monitors
    

    returns [{'left': 0, 'top': 0, 'width': 1680, 'height': 1050}, {'left': 0, 'top': 0, 'width': 1680, 'height': 1050}]

    Full message

    N/A
    

    Other details

    So far this is the only computer I've tested this on that has this issue, and it's the only hi-DPI computer I own.

    bug macOS 
    opened by edelmanjm 16
  • Massive memory usage when using MSS with queues

    Massive memory usage when using MSS with queues

    General informations:

    • OS name: macOS
    • OS version: 10.12.5 "Sierra"
    • OS architecture: 64 bits
    • Result of the command python --version: Python 2.7.10, however python3 --version yields Python 3.6.2 (which is what was used.)

    For GNU/Linux users:

    • Desktop Environment: Quartz

    Description of the warning/error

    Putting and removing images captured using MSS in a queue results in a massive memory usage. This example code resulted in about 6GB used in less that 15 seconds.

    from mss import mss
    import time
    import queue
    
    myqueue = queue.Queue()
    
    while True:
        with mss() as sct:
            myqueue.put(sct.shot())
        time.sleep(0.25)
        print(myqueue.get())
    

    Full message

    N/A
    

    Other details

    Willing to provide more info as needed!

    bug macOS 
    opened by edelmanjm 14
  • combined monitor image and mss().monitors incorrect

    combined monitor image and mss().monitors incorrect

    General information:

    • OS name: Windows 10
    • OS version: 10.0.17134.523
    • OS architecture: x64
    • Resolutions:
      • Monitor 1: 1600x900
      • Monitor 2: 1920x1080
    • Python version: 3.7.0
    • MSS version: 4.0.1

    The combined monitor image is rendering incorrectly and (because?) the monitors property returns invalid results.

    If you look at my output from print(sct.monitors) you will see the results are impossible:

    [{'left': 0, 'top': -172, 'width': 3520, 'height': 1252}, {'left': 0, 'top': 0, 'width': 1600, 'height': 900}, {'left': 1600, 'top': -172, 'width': 1920, 'height': 1080}]

    If I understand correctly, this output is saying that monitor 2 lies outside of the combination of all monitors together, which of course is impossible. I think this is what causes the 172-pixel black bar along the bottom of the image.

    fullscreen

    I think the correct output of mss().monitors should be:

    [{'left': 0, 'top': 0, 'width': 3520, 'height': 1080}, {'left': 0, 'top': 172, 'width': 1600, 'height': 900}, {'left': 1600, 'top': 0, 'width': 1920, 'height': 1080}]

    here is a screenshot of my monitor position in windows display manager:

    image

    bug Windows help welcome :) 
    opened by grintor 13
  • XGetImage() failed when using mss

    XGetImage() failed when using mss

    General information:

    • OS name: _Debian GNU/Linux_Ubuntu
    • OS version: 18.10
    • OS architecture: 64 bits
    • Resolutions:
      • Monitor 1: 1920x1080
      • Monitor 2: 1920x1080
    • Python version: 3.7.1
    • MSS version: 4.0.2

    For GNU/Linux users:

    • Display server protocol and version, if known: X server wayland
    • Desktop Environment: Unity
    • Composite Window Manager name and version: [not sure, it's gonna be whatever ubuntu 18.10 uses by default - I haven't configured any of this stuff]

    Description of the warning/error

    When I use any screen capture command (grab(), shot()), I get an error that XGetImage failed. code: pipenv install mss

    and in file process.py, I have taken some code straight the examples in documentation:

    import mss
    with mss.mss() as sct:
        try:
            filename = sct.shot(mon=-1, output='fullscreen.png')
            print(filename)
        except Exception as e:
            print(e, "\n", e.details)
    

    The above code outputs this:

    XGetImage() failed
     {'retval': <mss.linux.LP_XImage object at 0x7fc72d567bf8>, 'args': (<mss.linux.LP_Display object at 0x7fc72db7d1e0>, <mss.linux.LP_Display object at 0x7fc72d567950>, 0, 0, 1920, 1080, 16777215, 2)}
    

    And the stracktrace looks like this:

    Traceback (most recent call last):
      File "process.py", line 3, in <module>
        filename = sct.shot(mon=-1, output='fullscreen.png')
      File "/home/f41lurizer/.local/share/virtualenvs/poker-TAtsjijf/lib/python3.7/site-packages/mss/base.py", line 140, in shot
        return next(self.save(**kwargs))
      File "/home/f41lurizer/.local/share/virtualenvs/poker-TAtsjijf/lib/python3.7/site-packages/mss/base.py", line 129, in save
        sct = self.grab(monitor)
      File "/home/f41lurizer/.local/share/virtualenvs/poker-TAtsjijf/lib/python3.7/site-packages/mss/linux.py", line 430, in grab
        ZPIXMAP,
      File "/home/f41lurizer/.local/share/virtualenvs/poker-TAtsjijf/lib/python3.7/site-packages/mss/linux.py", line 171, in validate
        raise ScreenShotError(err, details=details)
    mss.exception.ScreenShotError: XGetImage() failed
    

    Other details

    I have also tried running as root, and running outside of tmux. Neither of these things changed the error I'm getting. I wonder if this has something to do with using wayland? On pyscreenshot, they seem to have limited support for screenshots on wayland.

    GNU/Linux 
    opened by mazjindeel 12
  • AttributeError: _data /

    AttributeError: _data / "gdi32.GetDIBits() failed" (Windows)

    General information:

    • OS name: Windows
    • OS version: 10, version 1803
    • OS architecture: 64-bit
    • Resolutions:
      • Monitor 1: 1920x1080
      • Monitor 2: 1920x1080
    • Python version: 3.6.5
    • MSS version: 3.2.1

    Description of the warning/error

    MSS consistently throws the following error, always after my program has been running for a little over 3 hours, and after successfully capturing many (22,000+) screenshots in that time.

    Full message

    == 2018-07-15 07:17:17.953381 runtime: 3:09:39.428722 ==
    ('gdi32.GetDIBits() failed.', {'bits': 0, 'height': 665, 'width': 1033, 'gdi': <WinDLL 'gdi32', handle 7ffeff9b0000 at 0x1e9c1896898>, 'monitor': {'left': -1034, 'top': 31, 'width': 1033, 'height': 665}, 'self': <mss.windows.MSS object at 0x000001E9C1896860>})
    Traceback (most recent call last):
      File "D:\IdeaProjects\Python\CaptureTest\main.py", line 98, in <module>
        run()
      File "D:\IdeaProjects\Python\CaptureTest\main.py", line 82, in run
        self.screenshot()
      File "D:\IdeaProjects\Python\CaptureTest\main.py", line 77, in screenshot
        self.im = self.window.screenshot()
      File "D:\IdeaProjects\Python\CaptureTest\main.py", line 84, in screenshot
        im = self.mss_instance.grab(area)
      File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\mss\windows.py", line 202, in grab
        del self._data
    AttributeError: _data
    

    Other details

    I've tried to replicate this error by simply calling mss.grab(...) in a while loop and seeing if it breaks after x number of screenshots, but that runs fine for at least 160,000 iterations, so I can't figure out why my program consistently seems to break at ~3 hours runtime.

    Upon viewing the MSS source, I realised that the del self._data line is directly followed by raise ScreenShotError('gdi32.GetDIBits() failed.', locals()), so I suppose my question is:

    What could cause gdi32.GetDIBits() to spontaneously fail?

    bug Windows help welcome :) 
    opened by HatScripts 11
  • Possible to save frames from videos with a high FPS?

    Possible to save frames from videos with a high FPS?

    from time import time
    import mss
    import mss.tools
    
    start = time()
    count = 1
    
    while True:
    	with mss.mss() as sct:
    	    # The screen part to capture
    	    monitor = {'top': 144, 'left': 80, 'width': 1397, 'height': 782}
    	    output = 'frames/sct-{}.png'.format(count)
    	    count += 1
    	    # Grab the data
    	    sct_img = sct.grab(monitor)
    
    	    # Save to the picture file
    	    mss.tools.to_png(sct_img.rgb, sct_img.size, output)
    	    # print(output)
    	    now = time()
    	    if (now - start) % 60 >= 10: break
    

    This seems to save only around 100 frames for 10 seconds. Can this be improved?

    enhancement help welcome :) 
    opened by tejaskhot 11
  • [WINDOWS] enable hi-dpi awareness for fullscreen shots. Fixes #57

    [WINDOWS] enable hi-dpi awareness for fullscreen shots. Fixes #57

    Changes proposed in this PR

    • Fixes #57

    Apologies on the following items - but I suspect this PR does not make any changes that impact them :)

    It is very important to keep up to date tests and documentation.

    • [ ] Tests added/updated
    • [ ] Documentation updated

    Is your code right?

    • [ ✔️ ] PEP8 compliant
    • [ ✔️ ] flake8 passed (bonus)
    • [ ✔️ ] pylint passed (bonus)
    enhancement Windows 
    opened by ryanfox 10
  • robustness to MSSWindows.get_pixels

    robustness to MSSWindows.get_pixels

    shouldn't there by a try/except around the objects created and clean-up? otherwise if an exception happens between the two the objects will leak, and object leaks are not good on windows :)

    bug Windows 
    opened by thehesiod 9
  • Screenshots have poor color accuracy

    Screenshots have poor color accuracy

    General information:

    • OS name: MacOS
    • OS version: 13.0.1
    • OS architecture: ARM
    • Resolutions:
      • Monitor 1: 2560 x 1664
    • Python version: 3.9.15
    • MSS version: 7.0.1

    Description of the warning/error

    Colors get washed out when taking monitor captures

    Full message

    Running the numpy / opencv sample code from the documentation and noticed that the color gets extremely washed out. The macbook I am running this on has a 10-bit panel. Perhaps some of this information could be getting lost, but I am not quite sure.

    Screenshot 2022-12-30 at 6 23 17 PM

    Code Used

    import cv2
    import numpy
    
    import mss
    import time
    with mss.mss() as sct:
        # Part of the screen to capture
        monitor = {"top": 40, "left": 0, "width": 800, "height": 640}
    
        while "Screen capturing":
            last_time = time.time()
    
            # Get raw pixels from the screen, save it to a Numpy array
            img = numpy.array(sct.grab(monitor))
    
            # Display the picture
            cv2.imshow("OpenCV/Numpy normal", img)
    
            # Display the picture in grayscale
            # cv2.imshow('OpenCV/Numpy grayscale',
            #            cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY))
    
            print(f"fps: {1 / (time.time() - last_time)}")
    
            # Press "q" to quit
            if cv2.waitKey(25) & 0xFF == ord("q"):
                cv2.destroyAllWindows()
                break
    
    macOS help welcome :) 
    opened by wkaisertexas 2
  • Unjustified Screenshot error after closing a Tkinter Toplevel (Linux)

    Unjustified Screenshot error after closing a Tkinter Toplevel (Linux)

    General information:

    • OS name: Ubuntu Linux
    • OS version: 22.04
    • OS architecture: 64 bits
    • Resolutions:
      • Monitor 1: 3440x1440 (issue occurs at all resolutions)
    • Python version: 3.10.6
    • MSS version: 6.1.0 & 7.0.1

    For GNU/Linux users:

    • Display server protocol and version, if known: X11 server
    • Desktop Environment: ubuntu:GNOME
    • Composite Window Manager name and version: X.Org v: 1.21.1.3, compositor: gnome-shell v: 42.5

    Description of the warning/error

    --- The issue (and solution) is described in detail here ---

    In summary, the following error occurs when trying to instantiate an mss object after opening/closing a Tkinter Toplevel window. This error does not occur on Windows.

    Full message

      File "/home/my_project/src/utilities/geometry.py", line 64, in screenshot
        with mss.mss() as sct:
      File "/home/my_project/env/lib/python3.10/site-packages/mss/factory.py", line 34, in mss
        return linux.MSS(**kwargs)
      File "/home/my_project/env/lib/python3.10/site-packages/mss/linux.py", line 297, in __init__
        self.root = self.xlib.XDefaultRootWindow(self._get_display(display))
      File "/home/my_project/env/lib/python3.10/site-packages/mss/linux.py", line 184, in validate
        raise ScreenShotError(f"{func.__name__}() failed", details=details)
    mss.exception.ScreenShotError: XDefaultRootWindow() failed
    
    Screenshot error: XDefaultRootWindow() failed, {'retval': <mss.linux.LP_XWindowAttributes object at 0x7f31d8d38ac0>, 
        'args': (<mss.linux.LP_Display object at 0x7f31d8d38740>,)}
    

    Other details

    The following code can be used to reproduce the error. Simply run this program and use the GUI button to open a new window that allows you to take a screenshot - then close the pop-up window and attempt to repeat the process.

    import tkinter as tk
    
    import mss
    import mss.tools
    
    
    def take_screenshot():
       with mss.mss() as sct:
           screen_part = {"top": 370, "left": 1090, "width": 80, "height": 390}
           sct_img = sct.grab(screen_part)
           mss.tools.to_png(sct_img.rgb, sct_img.size, output="./output.png")
    
    def create_top_level_win():
       top_level_win = tk.Toplevel(root)
    
       take_screenshot_btn = tk.Button(top_level_win, text="Take screenshot", command=take_screenshot)
       take_screenshot_btn.pack()
    
    root = tk.Tk()
    
    btn = tk.Button(root, text="Open TopLevel", command=create_top_level_win)
    btn.pack()
    
    root.mainloop()
    

    A temporary workaround is to reuse a single mss object throughout the application, like so:

    sct = mss.mss()
    
    def take_screenshot():
        global sct
        screen_part = {"top": 370, "left": 1090, "width": 80, "height": 390}
        sct_img = sct.grab(screen_part)
        mss.tools.to_png(sct_img.rgb, sct_img.size, output="./output.png")
    

    On StackOverflow, one answer suggests that the bug is due to "the current implementation of MSS changing the current X11 error handler and leaving it afterwards, which causes a conflict with Tcl/Tk (the backend of Python Tkinter), see here for details"

    bug GNU/Linux 
    opened by kelltom 1
  • monitors Width and height errors when two monitors have different DPI

    monitors Width and height errors when two monitors have different DPI

    General information:

    • OS name: _Windows11

    • OS version: sid

    • OS architecture: 64 bits

    • Resolutions:

      • Monitor 1: 3840x2160 DPI 200%
      • Monitor 2: 2560x1440 DPI 175%
    • Python version: 3.10.9

    • MSS version: 3.2.0

      mss_scr = mss.mss() print(mss_scr.monitors)

    [{'left': -2926, 'top': 0, 'width': 6766, 'height': 2160}, {'left': 0, 'top': 0, 'width': 3840, 'height': 2160}, {'left': -2926, 'top': 0, 'width': 2926, 'height': 1646}] <===== It is actually 2560*1440

    bug Windows help welcome :) 
    opened by bluely1978 1
  • Bad cached BMP: gdi32.GetDIBits() failed (Sourcery refactored)

    Bad cached BMP: gdi32.GetDIBits() failed (Sourcery refactored)

    Pull Request #211 refactored by Sourcery.

    Since the original Pull Request was opened as a fork in a contributor's repository, we are unable to create a Pull Request branching from it.

    To incorporate these changes, you can either:

    1. Merge this Pull Request instead of the original, or

    2. Ask your contributor to locally incorporate these commits and push them to the original Pull Request

      Incorporate changes via command line
      git fetch https://github.com/BoboTiG/python-mss pull/211/head
      git merge --ff-only FETCH_HEAD
      git push

    NOTE: As code is pushed to the original Pull Request, Sourcery will re-run and update (force-push) this Pull Request with new refactorings as necessary. If Sourcery finds no refactorings at any point, this Pull Request will be closed automatically.

    See our documentation here.

    Run Sourcery locally

    Reduce the feedback loop during development by using the Sourcery editor plugin:

    Help us improve this pull request!

    opened by sourcery-ai[bot] 1
  • How would I save the frames to a video file?

    How would I save the frames to a video file?

    General information:

    • OS name: Windows 10
    • OS architecture: 64 bits
    • Resolutions:
      • Monitor 1: 1920x1080
    • Python version: 3.11
    • MSS version: newest

    Full message

    Rather a question would be nice if I got some help 
    
    opened by Maxhem2 0
  • How to increase FPS? FPS is limited to monitor Frame Rate

    How to increase FPS? FPS is limited to monitor Frame Rate

    General information:

    • OS name: Windows 10 Pro
    • OS version: 19043.1889/21H1
    • OS architecture: 64 bits
    • Resolutions:
      • Monitor 1: 3840x2160 60Hz
      • Monitor 2: 1920x1080 60Hz
    • Python version: 3.7.0
    • MSS version: 6.1.0
    • Videocard: Gigabyte 3080ti
    • CPU: AMD Ryzen 7 5800x

    Description

    I try to use MSS library to capture screen game on my Windows PC, however capture frame rates are not getting higher than 60FPS. Although game is running on 160 FPS, MSS is limited to only 60.

    I tried:

    1. Changing Monitor Framerate to 30 and mss fps also dropped to 30.
    2. Changing Monitor resolution, nothing changed
    3. Changing size of screen capture (Region of Interest), it did not change FPS

    So I suspect, the problem is not Hardware related and limitation comes from software.

    Code

        width = 512 # roi
        height = 512  # roi
        mon = {
            # "left": int(3840 / 2 - width / 2),
            # "top": int(2160 / 2 - height / 2),
            "left": int(1920 / 2 - width / 2),
            "top": int(1080 / 2 - height / 2),
            "width": width,
            "height": height,
        }
    
        sct = mss()
        fps = [i for i in range(30)]
        index = 0
        prev_bytes = None
        while True:
            if (
                not disabed_capture
            ):
                start_time = time.time()
                _bytes = sct.grab(mon)
                if prev_bytes is not None and _bytes == prev_bytes:
                    print("SAME!")
                    continue
                prev_bytes = _bytes
                frame = np.array(_bytes)
                queue.put([time.time(), frame])
                index = (index + 1) % len(fps)
                fps[index] = 1 / (time.time() - start_time)
                if index % 30 == 0:
                    print("SCREENSHOT FPS: ", sum(fps) / len(fps))
    
    help welcome :) 
    opened by DavraYoung 3
Releases(v7.0.1)
  • v7.0.1(Oct 27, 2022)

  • v7.0.0(Oct 27, 2022)

    :heart: contributors: @CTPaHHuK-HEbA, @Tonyl314, @ArchangeGabriel

    • :snake: added support for Python 3.11
    • :snake: added support for Python 3.10
    • :warning: removed support for Python 3.5
    • MSS: modernized the code base (types, f-string, ran isort & black) (close #101)
    • MSS: fixed several Sourcery issues
    • MSS: fixed typos here, and there
    • doc: fixed an error when building the documentation
    Source code(tar.gz)
    Source code(zip)
  • v6.1.0(Oct 31, 2020)

    • MSS: reworked how C functions are initialised
    • Mac: reduce the number of function calls
    • Mac: support macOS Big Sur (fixes #178)
    • tests: expand Python versions to 3.9 and 3.10
    • tests: fix macOS intepreter not found on Travis-CI
    • tests: fix test_entry_point() when there are several monitors
    Source code(tar.gz)
    Source code(zip)
  • v6.0.0(Jun 30, 2020)

    • removed usage of deprecated license_file option for license_files
    • fixed flake8 usage in pre-commit
    • the module is now available on conda (closes #170)
    • MSS: the implementation is now thread-safe on all OSes (fixes #169)
    • Linux: better handling of the Xrandr extension (fixes #168)
    • tests: fixed a random bug on test_grab_with_tuple_percents() (fixes #142)
    Source code(tar.gz)
    Source code(zip)
  • v5.1.0(Apr 30, 2020)

    :heart: contributors: @narumishi

    • :snake: produce wheels for Python 3 only
    • MSS: renamed again MSSMixin to MSSBase, now derived from abc.ABCMeta
    • tools: force write of file when saving a PNG file
    • tests: fix tests on macOS with Retina display
    • Windows: fixed multi-thread safety (fixes #150)
    Source code(tar.gz)
    Source code(zip)
  • v5.0.0(Dec 31, 2019)

    :heart: contributors: @hugovk, @foone, @SergeyKalutsky

    • :warning: removed support for Python 2.7
    • MSS: improve type annotations and add CI check
    • MSS: use __slots__ for better performances
    • MSS: better handle resources to prevent leaks
    • MSS: improve monitors finding
    • Windows: use our own instances of GDI32 and User32 DLLs
    • doc: add project_urls to setup.cfg
    • doc: add an example using the multiprocessing module (closes #82)
    • tests: added regression tests for #128 and #135
    • tests: move tests files into the package
    Source code(tar.gz)
    Source code(zip)
  • v4.0.3(Apr 23, 2019)

    :warning: The source code is now derived from master, where Python 2 support has been dropped.

    • new contributors: @grintor, @SergeyKalutsky
    • Windows: use our own instances of GDI32 and User32 DLLs (backported from 5.0.0)
    • Windows: fix the screen bounding AiO rectangle (backported from 5.0.0)
    Source code(tar.gz)
    Source code(zip)
  • v4.0.2(Feb 23, 2019)

  • v4.0.1(Jan 26, 2019)

    • Linux: fix several XLib functions signature (fixes #92)
    • Linux: improve monitors finding by a factor of 44
    • Linux: fix pylint error "Using variable 'validate' before assignment"
    • tests: removed PyPy from the testing matrix
    • tests: fixed Travis-CI with Xvfb
    • tests: do not allow any failure
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0(Jan 11, 2019)

    • MSS: remove use of setup.py for setup.cfg
    • MSS: renamed MSSBase to MSSMixin in base.py
    • MSS: refactor ctypes argtype, restype and errcheck setup (fixes #84)
    • Linux: ensure resources are freed in grab()
    • Windows: avoid unecessary class attributes
    • MSS: ensure calls without context manager will not leak resources or document them (fixes #72 and #85)
    • MSS: fix Flake8 C408: Unnecessary dict call - rewrite as a literal, in exceptions.py
    • MSS: fix Flake8 I100: Import statements are in the wrong order
    • MSS: fix Flake8 I201: Missing newline before sections or imports
    • MSS: fix PyLint bad-super-call: Bad first argument 'Exception' given to super()
    • tests: use tox, enable PyPy and PyPy3, add macOS and Windows CI
    Source code(tar.gz)
    Source code(zip)
  • v3.3.2(Nov 20, 2018)

    • new contributors: @hugovk, @andreasbuhr
    • MSS: do monitor detection in MSS constructor (fixes #79)
    • MSS: specify compliant Python versions for pip install
    • tests: enable Python 3.7
    • tests: fix test_entry_point() with multiple monitors
    Source code(tar.gz)
    Source code(zip)
  • v3.3.1(Sep 22, 2018)

  • v3.3.0(Sep 4, 2018)

    • Linux: add an error handler for the XServer to prevent interpreter crash (fix #61)
    • MSS: fix a ResourceWarning: unclosed file in setup.py
    • tests: fix a ResourceWarning: unclosed file
    • doc: fix a typo in Screenshot.pixel() method (thanks to @mchlnix)
    • big code clean-up using black
    Source code(tar.gz)
    Source code(zip)
  • v3.2.1(May 21, 2018)

  • v3.2.0(Mar 22, 2018)

    • :warning: removed support for Python 3.4
    • MSS: add the Screenshot.bgra attribute
    • MSS: speed-up grabbing on the 3 platforms
    • tools: add PNG compression level control to to_png()
    • tests: add leaks.py and benchmarks.py for manual testing
    • doc: add an example about capturing part of the monitor 2
    • doc: add an example about computing BGRA values to RGB
    Source code(tar.gz)
    Source code(zip)
  • v3.1.2(Jan 5, 2018)

    • :warning: removed support for Python 3.3
    • CI: build the documentation
    • doc: improvements and fixes (fix #37)
    • MSS: possibility to get the whole PNG raw bytes
    • Windows: capture all visible windows
    Source code(tar.gz)
    Source code(zip)
  • v3.1.1(Jan 5, 2018)

    • new contributor: @karanlyons
    • MSS: add the mss entry point
    • MSS: add more way of customization to the output argument of save()
    • MSS: possibility to use custom class to handle screen shot data
    • Mac: properly support all display scaling and resolutions (fix #14, #19, #21, #23)
    • Mac: fix memory leaks (fix #24)
    • Linux: handle bad display value
    • Windows: Take into account zoom factor for high-DPI displays (fix #20)
    • add the 'Say Thanks' button
    • doc: several fixes (fix #22)
    • tests: a lot of tests added for better coverage
    Source code(tar.gz)
    Source code(zip)
  • v3.0.1(Jan 5, 2018)

  • v2.0.22(Jan 5, 2018)

    • new contributors: @DavideBecker, @redodo
    • add an example to capture only a part of the screen
    • better use of exception mechanism
    • Linux: use of hasattr to prevent Exception on early exit
    • Mac: take into account extra black pixels added when screen with is not divisible by 16 (fix #14)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.18(Jan 5, 2018)

    • new contributor: @cycomanic
    • change license to MIT
    • Linux: remove MSS library
    • Linux: insanely fast using only ctypes
    • Linux: skip unused monitors
    • Linux: use errcheck instead of deprecated restype with callable (fix #11)
    • Linux: fix security issue (reported by Bandit)
    • add type hints
    • add documentation (fix #10)
    • add tests and use Travis CI (fix #9)
    • remove unused code (reported by Vulture)
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jan 5, 2018)

    • split the module into several files
    • add issue and pull request templates
    • a lot of code refactor and optimizations
    • MSS: rename save_img() to to_png()
    • MSS: save(): replace screen argument by mon
    • Mac: get rid of the PyObjc module, 100% ctypes
    • Linux: prevent segfault when DISPLAY is set but no X server started
    • Linux: prevent segfault when Xrandr is not loaded
    • Linux: get_pixels() insanely fast, use of MSS library (C code)
    • Windows: fix #6, screen shot not correct on Windows 8
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Jan 5, 2018)

  • v1.0.1(Jan 5, 2018)

  • v1.0.0(Jan 5, 2018)

    • :snake: Python 2.6 to 3.5 ready
    • code purgation and review, no more debug informations
    • delete --debug argument
    • MSS: fix #5, add a shortcut to take automatically use the proper MSS class
    • MSS: few optimizations into save_img()
    • Mac: remove rotation from informations returned by enum_display_monitors()
    • Linux: fix object has no attribute display into __del__
    • Linux: use of XDestroyImage() instead of XFree()
    • Linux: optimizations of get_pixels()
    • Windows: huge optimization of get_pixels()
    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Jan 5, 2018)

  • v0.1.0(Jan 5, 2018)

    • fix code with YAPF tool
    • better tests and examples
    • Linux: fully functional using Xrandr library
    • Linux: code purgation (no more XML files to parse)
    Source code(tar.gz)
    Source code(zip)
  • v0.0.8(Jan 5, 2018)

    • new contributors: @sergey-vin, @thehesiod
    • MSS: fix #3, filename's dir is not used when saving
    • MSS: fix E713 test for membership should be 'not in'
    • MSS: raise an exception for unimplemented methods
    • Windows: fix #4, robustness to MSSWindows.get_pixels
    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Jan 5, 2018)

  • v0.0.6(Jan 5, 2018)

    • new contributor: @sametmax
    • PEP8 compliant
    • Python 3.4 ready
    • review module structure to fit the "Code Like a Pythonista: Idiomatic Python"
    • refactoring of all enum_display_monitors() methods
    • fix misspellings using codespell tool
    • possibility to append --debug to the command line
    • better way to manage output filenames (callback)
    • several fixes here and there, code refactoring
    • MSS: moved into a MSS:save_img() method
    • Linux: add XFCE4 support
    Source code(tar.gz)
    Source code(zip)
  • v0.0.5(Jan 5, 2018)

Owner
Mickaël Schoentgen
Python Desktop Application Developer. Creator of Python module MSS, FOSS contributor. https://ghuser.io/BoboTiG
Mickaël Schoentgen
Search and Find Jobs in Ethiopia

✨ EthioJobs ✨ Search and Find Jobs in Ethiopia Easy start critical warning Use pycharm No vscode No sublime No Vim No nothing when you want to use

Abdimk 12 Nov 09, 2022
Developed a website to analyze and generate report of students based on the curriculum that represents student’s academic performance.

Developed a website to analyze and generate report of students based on the curriculum that represents student’s academic performance. We have developed the system such that, it will automatically pa

VIJETA CHAVHAN 3 Nov 08, 2022
Python based scripts for obtaining system information from Linux.

sysinfo Python based scripts for obtaining system information from Linux. Python2 and Python3 compatible Output in JSON format Simple scripts and exte

Petr Vavrin 70 Dec 20, 2022
Annotates sequences with Eggnog-mapper and hhblits against PDB70

Annotating "hypothetical" proteins with the PDB See config/ for configuration information. This workflow takes as input a set of protein sequences. It

1 Apr 05, 2022
Python project setup, updater, and launcher

pyLaunch Python project setup, updater, and launcher Purpose: Increase project productivity and provide features easily. Once installed as a git submo

DAAV, LLC 1 Jan 07, 2022
Class XII computer science project.

Computer Science Project — Class XII Kshitij Srivastava (XI – A) Introduction The aim of this project is to create a fully operational system for a me

Kshitij Srivastava 2 Jul 21, 2022
An OrpheusDL Tidal module

OrpheusDL - Tidal A Tidal module for the OrpheusDL modular archival music program Report Bug · Request Feature Table of content About OrpheusDL - Tida

Daniel 54 Dec 29, 2022
A play store search module

A play store search module

Fayas Noushad 5 Dec 01, 2021
Meaningful and minimalist release notes for developers

Managing manual release notes is hard. Therefore, everyone tends to generate release notes from commit messages. But, you won't get a meaningful release note at the end.

codezri 31 Dec 30, 2022
原神抽卡记录导出

原神抽卡记录导出 抽卡记录分析工具 from @笑沐泽 抽卡记录导出工具js版,含油猴脚本可在浏览器导出 注意:我的是python版,带饼图的是隔壁electron版,功能类似 Wik

834 Jan 04, 2023
A shim for the typeshed changes in mypy 0.900

types-all A shim for the typeshed changes in mypy 0.900 installation pip install types-all why --install-types is annoying, this installs all the thin

Anthony Sottile 28 Oct 20, 2022
It's like Forth but in Python

It's like Forth but written in Python. But I don't actually know for sure since I never programmed in Forth, I only heard that it's some sort of stack-based programming language. Porth is also stack-

Tsoding 619 Dec 21, 2022
Shutdown Time - A pretty much useless application that allows you to shut your computer down in x time with a GUI.

A pretty much useless application that allows you to shut your computer down in x time with a GUI. Should eventually support Windows (all versions), Linux (v2.0+), MacOS (probably with Linux, idk)

1 Nov 08, 2022
Very Simple Zoom Spam Pinger!

Very Simple Zoom Spam Pinger!

Syntax. 2 Mar 05, 2022
Data Poisoning based on Adversarial Attacks using Non-Robust Features

Data Poisoning based on Adversarial Attacks using Non-Robust Features Usage python main.py [-h] [--gpu | -g GPU] [--eps |-e EPSILON] [--pert | -p PER

Jonathan E. 1 Nov 02, 2021
Medical appointments No-Show classifier

Medical Appointments No-shows Why do 20% of patients miss their scheduled appointments? A person makes a doctor appointment, receives all the instruct

4 Apr 20, 2022
Flight Reservation App With Python

Flight Reservation App With Python

victor-h. 1 Nov 21, 2021
Block the annoying Token Grabbers on your discord

General We have seen that in the last time many discord servers are infected by fake discord nitro links we want to put an end to this and have develo

BadTiger Network 2 Jul 16, 2022
Tie together `drf-spectacular` and `djangorestframework-dataclasses` for easy-to-use apis and openapi schemas.

Speccify Tie together drf-spectacular and djangorestframework-dataclasses for easy-to-use apis and openapi schemas. Usage @dataclass class MyQ

Lyst 4 Sep 26, 2022
*考研学习利器,玩电脑控制不住自己时,可以使用该程序定日期锁屏,同时有精美壁纸锁屏显示,也不会枯燥。

LockscreenbyTime_win10 A python program in win10. You can set the time to lock the computer(by setting year, month, day), Fullscreen pictures will sho

PixianDouban 4 Jul 10, 2022