Giter Club home page Giter Club logo

python-capture-device-list's Introduction

Getting Camera List and Resolution in Python on Windows

OpenCV does not have an API for enumerating capture devices. The sample shows how to create a Python extension to invoke DirectShow C++ APIs for enumerating capture devices and corresponding resolutions.

Environment

How to Build the CPython Extension

  • Create a source distribution:

    python setup.py sdist
  • distutils:

    python .\setup_distutils.py build
  • scikit-build:

    pip wheel . --verbose

Test

import device
import cv2

def select_camera(last_index):
    number = 0
    hint = "Select a camera (0 to " + str(last_index) + "): "
    try:
        number = int(input(hint))
        # select = int(select)
    except Exception:
        print("It's not a number!")
        return select_camera(last_index)

    if number > last_index:
        print("Invalid number! Retry!")
        return select_camera(last_index)

    return number


def open_camera(index):
    cap = cv2.VideoCapture(index)
    return cap

def main():
    # print OpenCV version
    print("OpenCV version: " + cv2.__version__)

    # Get camera list
    device_list = device.getDeviceList()
    index = 0

    for camera in device_list:
        print(str(index) + ': ' + camera[0] + ' ' + str(camera[1]))
        index += 1

    last_index = index - 1

    if last_index < 0:
        print("No device is connected")
        return

    # Select a camera
    camera_number = select_camera(last_index)
    
    # Open camera
    cap = open_camera(camera_number)

    if cap.isOpened():
        width = cap.get(3) # Frame Width
        height = cap.get(4) # Frame Height
        print('Default width: ' + str(width) + ', height: ' + str(height))

        while True:
            
            ret, frame = cap.read()
            cv2.imshow("frame", frame)

            # key: 'ESC'
            key = cv2.waitKey(20)
            if key == 27:
                break

        cap.release() 
        cv2.destroyAllWindows() 

if __name__ == "__main__":
    main()
python test.py

camera list in Python

Blog

Listing Multiple Cameras for OpenCV-Python on Windows

python-capture-device-list's People

Contributors

yushulx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

python-capture-device-list's Issues

The camera index isn't match with the real devices

I tried to build and installed on my laptop. And it seems that the listed camera isn't match the real devices, or at least the index which opencv uses. Below is the output:

Before inserting the USB camera:
❯ python .\test.py
OpenCV version: 4.5.5
0: HP HD Camera [(640, 480), (320, 180), (320, 240), (424, 240), (640, 360), (640, 480), (320, 180), (320, 240), (424, 240), (640, 360), (848, 480), (960, 540), (1280, 720)]
Select a camera (0 to 0): 0
Default width: 640.0, height: 480.0
[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (539) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

After inserting the USB camera:

❯ python .\test.py
OpenCV version: 4.5.5
0: USB Camera [(1280, 720), (800, 600), (640, 480), (352, 288), (320, 240), (176, 144), (160, 120), (1280, 720), (800, 600), (640, 480), (352, 288), (320, 240), (176, 144), (160, 120), (1280, 720), (800, 600), (640, 480), (352, 288), (320, 240), (176, 144), (160, 120), (1280, 720), (800, 600), (640, 480), (352, 288), (320, 240), (176, 144), (160, 120)]
1: HP HD Camera [(640, 480), (320, 180), (320, 240), (424, 240), (640, 360), (640, 480), (320, 180), (320, 240), (424, 240), (640, 360), (848, 480), (960, 540), (1280, 720)]
Select a camera (0 to 1): 0
Default width: 640.0, height: 480.0
[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (539) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

the test.py is the sample code in the repo README file.
After inserting the USB Camera, it seems the second webcam took the "0" index, and the integrated one became "1". But actually, the programs calls the integrated cam(i.e. HP HD Camera) when I input "0", and calls USB Camera when i input "1".

python version is 3.10.4, windows-capture-device-list is 1.1.0 and OS is windows 10.

Is there any idea how I can fix it?

If you're usind PyQt and Visual Studio Code

I am doing an application using PySide2 and Visual Studio Code which needs to detect automatically a very specific device. I spent some days trying to make this work, and in the end, I did.

If you're doing something similar to my app, this is for you:

1 - Download Visual Studio version 2022 or newer: I tried to just install the VS2015 Tools, but it didn't work at all, so I downloaded the most recent version of the IDE.

2 - Build the "setup.py" file on Visual Studio 2022: You need to open the folder of the test project and run the following line on the terminal "python setup.py build install" just as described prior. You don't need to run "SET VS90COMNTOOLS=%VS100COMNTOOLS%" or nothing similar if you're using VS2022.

3 - Implement the module on your code: This is the tricky part, after you import "device" onto your code, you'd think that you could use it's functions anywhere, but unfortunately that's not the case. If you want to run the code at the start of the class, or even outside it, it should work just fine, but if using this code on your constructor (init) or even deeper, you will be graced with "returned NULL without setting an error". My solution was using the functions outside the main class and inside a thread, I don't know why, but it works.

Here's an example of what worked for my situation and what didn't:

import device

class MyCVThread(QThread):

def __init__(self, parent = None):
    QThread.__init__(self, parent)
    self.exiting = False
    self.deviceStatus = 'No device connected'

def run(self):

#here's where you should put those functions

    self.index = 0

    device_list = device.getDeviceList()
    print(device_list)
    for d in device_list:
        if d == "DEVICE_NAME":
            self.index = self.index
            break
        self.index += 1

    try:
        
        cap = cv2.VideoCapture(self.index, cv2.CAP_DSHOW)
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1600)#1024
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1200)#768
        print('running')

    except Exception as e:
        print(e)

class MainWindow(QMainWindow, Ui_MainWindow, QObject):

def __init__(self):
    QMainWindow.__init__(self)

         #If you call the functions here, **it will cause the error**, even if it's inside other functions ou called by signals

if name == "main":
app = QApplication(sys.argv)

mainWindow = MainWindow()

mainWindow.showMaximized()
mainWindow.show()

sys.exit(app.exec_())

PyInstaller Compatibility

Hello. Is this compatible with PyInstaller? I was able get this working with my project, but when using an .exe made by PyInstaller, the program doesn't get the list of devices.

One could skip step 1&2 to get started when using anaconda environment

Hi,

Thanks for sharing this wonderful repository. I want to share some tips for later users setting up the repository in anaconda environment.

The first step Configure Visual Studio environment and second step Add your Windows SDK lib path to setup.py could simply be skipped.

Best

Add DevicePath to output tuple

While yielding Description / FriendlyName is certainly user friendly, it's actually close to useless when you have more than a single camera in your system with the same vendor / model etc.

The index with which the device is enumerated isn't stable either, and will inevitably result in mixups in between device restarts.

In this case, DevicePath is required to correctly identify the DirectShow devices.

Failed to append the object item at the end of list list

Originally, I started to write this because of the following error:

OpenCV version: 4.2.0
Failed to append the object item at the end of list list
SystemError: c:\a\29\s\objects\listobject.c:353: bad argument to internal function

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test.py", line 133, in <module>
    main()
  File "test.py", line 30, in main
    device_list = device.getDeviceList()
SystemError: <built-in function getDeviceList> returned a result with an error set

But then I saw the similar issue with the option of using 'try' so I did the 'try' and got

Failed to append the object item at the end of list list
Traceback (most recent call last):
  File "test.py", line 137, in <module>
    main()
  File "test.py", line 37, in main
    for name in device_list:
NameError: name 'device_list' is not defined

So I decided to try (commented out device_list):

print(device.getDeviceList())

Output:

OpenCV version: 4.2.0
Failed to append the object item at the end of list list

I have 4 cameras attached. I'm doing this remotely so I can't unattach the cameras. This is using Windows 10 Pro latest version 1909 with all recent updates. I'd appreciate any input on this.

get UnicodeDecodeError

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 8: invalid start byte

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\test\d.py", line 2, in
print(device.getDeviceList())
SystemError: returned a result with an exception set

error: (-215:Assertion failed)

Encountered some errors during execution.

OpenCV version: 4.6.0
0: KS5A00N
1: KS5A00N
Select a camera (0 to 1): 1
Default width: 640.0, height: 480.0
[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (464) anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072875772 [ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (476) anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072875772
[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1752) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072875772
Traceback (most recent call last):
File "C:\Users\461100\Desktop\python-capture-device-list-master\test.py", line 68, in
main()
File "C:\Users\461100\Desktop\python-capture-device-list-master\test.py", line 57, in main
cv2.imshow("frame", frame)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion
failed) size.width>0 && size.height>0 in function 'cv::imshow

If you can provide any help, it will help me a lot, thank you very much.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.