Python获取摄像头设备

# coding:utf-8
import cv2
import tkinter as tk
from tkinter import ttk, messagebox

def list_cameras():
    index = 0
    arr = []
    while True:
        cap = cv2.VideoCapture(index, cv2.CAP_DSHOW)
        if not cap.isOpened():
            break
        else:
            arr.append(index)
        cap.release()
        index += 1
    return arr

def show_frame():
    global cap, camera_running
    if camera_running:
        ret, frame = cap.read()
        if ret:
            cv2.imshow("Capture_Paizhao", frame)
            cv2.waitKey(1)
        root.after(10, show_frame)
    else:
        cap.release()
        cv2.destroyAllWindows()

def start_camera(camera_index):
    global cap, camera_running
    cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
    if not cap.isOpened():
        messagebox.showerror("Error", "无法打开摄像头")
        return

    camera_running = True
    show_frame()

def stop_camera():
    global camera_running
    camera_running = False

def on_start_button_click():
    global camera_running
    if camera_running:
        stop_camera()
        start_button.config(text="直播")
    else:
        selected_index = camera_combobox.current()
        if selected_index == -1:
            messagebox.showwarning("Warning", "请选择一个摄像头")
        else:
            camera_index = cameras[selected_index]
            start_camera(camera_index)
            start_button.config(text="停止")

# 创建主窗口
root = tk.Tk()
root.title("Camera Selector")

# 初始化变量
cap = None
camera_running = False

# 获取可用摄像头列表
cameras = list_cameras()
if not cameras:
    messagebox.showerror("Error", "未找到摄像头")
    root.destroy()
else:
    # 创建下拉菜单
    camera_combobox = ttk.Combobox(root, values=[f"Camera {i}" for i in cameras], state="readonly")
    camera_combobox.grid(row=0, column=0, padx=10, pady=10)
    camera_combobox.current(0)  # 设置默认选择第一个摄像头

    # 创建启动按钮
    start_button = tk.Button(root, text="直播", command=on_start_button_click)
    start_button.grid(row=0, column=1, padx=10, pady=10)

# 运行主循环
root.mainloop()

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值