Francesco Vezzani
Francesco Vezzani

Reputation: 93

PYTHON - CV2 : Check if webcam is used by other app

I'm trying to develop a code to check if the WebCam is used by other app (like Zoom, Skype etc...) using python and cv2.

For example, in macOS you can use this command in the TERMINAL lsof | grep "VDC" to see if the WebCam is running.

So I don't want to open it like in this code

import numpy as np
import cv2

cap = cv2.VideoCapture(0)
if(cap.isOpened()):
    print("Camera conntected")
else:
    print("Alert ! Camera disconnected")`

I want only to check if it is opened by other app or is closed and print 'Running' or 'Not running'.

I prefer using python, but if there is other language fell free to report ;)

Upvotes: 1

Views: 1279

Answers (2)

Emilio Dalla Torre
Emilio Dalla Torre

Reputation: 146

At the moment macOS does not allow users to see which app is using system resources as the camera, for privacy reasons.

You could, anyway, check out this project that has achieved what you are looking for. Maybe, with a native implementation, you could be able to get the camera state or workaround it someway.

Upvotes: 1

Panda50
Panda50

Reputation: 939

even if it's not perfect, the "best" solution should be to use a try except and force it to 'bug' if the camera is already openned. I try to access the Warnings from cv2 but it looks a bit hard.

Here is a code that works in your case:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)
if(cap.isOpened()):
    print("Camera conntected")
else:
    print("Alert ! Camera disconnected")

number_itteration = 0
while cap.isOpened():
    try:
        ret, frame = cap.read()
        if number_itteration == 0:
            print(len(frame))
    except Exception as e:
        print('camera already used')
        break
    number_itteration += 1

Upvotes: 0

Related Questions