python - 有没有比 cv2.videocapture 不同的方法来检查相机状态?

标签 python opencv

我有一个在循环内执行 cv2.VideoCapture 的代码。这使得代码不断检查摄像头是否打开,这是摄像头未按应有的方式显示视频片段的原因。我在循环中有 cv2.VideoCapture,这样我就可以检测相机是否已连接。有没有办法解决这个问题,有什么方法可以检查我的网络摄像头是否已连接?

我尝试过多线程等,以获得进一步的成功。

一些代码:

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()

任何和所有的帮助将非常感激!

最佳答案

关于python - 有没有比 cv2.videocapture 不同的方法来检查相机状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58156557/

相关文章:

python - 解码Jpeg/内容: 0 'refers to a tensor that does not exist

python - 将原始 SQL 映射到多个相关的 Django 模型

c++ - QT Creator 中的部署和静态打包在单个可执行文件中链接 QT 和 OpenCV

OpenCV 2.4.9 和 CUDA 6.5

python - 如何使下面的代码工作

python - 使用 StringIO 对象保存 uu.encode/uu.decode 数据

python - 存储配置详细信息

android - 使用简单边缘检测 flutter 时出现运行时错误

c++ - 在 openCV 中为 oclMat 添加小图像到大图像

python - 为什么imread返回NULL?