GottaAimHigherPal
GottaAimHigherPal

Reputation: 125

Is there a different way to check camera status than cv2.videocapture?

I have a code that executes cv2.VideoCapture inside a loop. This makes it so the code constantly checks if the camera is open which is the cause to the camera not showing video footage as it should. I have the cv2.VideoCapture inside the loop so i can detect if the camera is connected or not. Is there a way around this, Any method to check if my webcam is connected or not?

I've tried multithreading and such with to further success.

Some code:

from tkinter import *  # Import the tkinter module (For the Graphical User Interface)
import cv2  # Import the cv2 module for web camera footage
import PIL  # Import the pillow library for image configuration.
from PIL import Image, ImageTk  # Import the specifics for Image configuration.

print("[INFO] Imports done")

width, height = 800, 600  # Define The width and height widget for cap adjustment
RootGeometry = str(width) + "x" + str(height)  # Make a variable to adjust tkinter frame
print("[INFO] Geometries made")

ImageSource = 0
cap = cv2.VideoCapture(ImageSource)  # First VideoCapture
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
print("[INFO] Cap set")

root = Tk()
print("[INFO] Window made")

root.title("Main Window")
root.configure(background="white")
root.geometry(RootGeometry)
root.bind('<Escape>', lambda e: root.quit())
lmain = Label(root)
lmain.pack()
print("[INFO] Configuration of cap done.")


def ShowFrame():
    ok, frame = cap.read()
    if ok:
        print("[INFO] Show frame Initialized.")

        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        img = PIL.Image.fromarray(cv2image)
        imgtk = ImageTk.PhotoImage(image=img)
        lmain.imgtk = imgtk
        lmain.configure(image=imgtk)
        print("[INFO] After 10 initializing")
        lmain.after(10, ShowFrame)
        print("[INFO] Showed image")

    else:
        lmain.after(10, CheckSource)


def CheckSource():
    print("[INFO] CheckSource Triggered.")
    capture = cv2.VideoCapture(ImageSource)
    if capture.isOpened():
        print("[INFO] [DEBUG] if Ok initialized")
        if cv2.waitKey(1) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            cv2.waitKey(0)
            print("[WARNING] Exiting app after command")

        ShowFrame()

    else:
        print("[WARNING] No source found. Looking for source.")
        lmain.after(10, CheckSource)


CheckSource()
root.mainloop()

Any and all help would be very appreceated!

Upvotes: 2

Views: 1154

Answers (1)

Sachin
Sachin

Reputation: 219

Can you check with below method,

cap.isOpened()

More info is at, https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

Upvotes: 2

Related Questions