在TkinterGUI界面显示WIFI网络摄像头(ESP32s3)视频画面

本实验结合了之前写过的两篇文章Python调用摄像头,实时显示视频在Tkinter界面以及ESP32 S3搭载OV2640摄像头释放热点(AP)工作模式--Arduino程序,当然如果手头有其他可以获得网络摄像头的URL即用于访问摄像头视频流的网络地址,也是一样的换掉网址即可。话不多说,上程序效果。

我是添加了两个按钮,通过点击"打开视频"按钮,可以开始捕获和显示视频流;点击"关闭视频"按钮,可以停止视频流并清除画布内容。

程序如下:

python 复制代码
import cv2
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk  # 图像控件

# 创建视频捕获对象,初始时 cap 为 None,表示摄像头关闭。
cap = None 

# 界面画布更新图像
def tkImage():
    global cap
    if cap is None:
        return None
    ref, frame = cap.read()
    if not ref:
        print("Failed to capture frame")
        return None
    frame = cv2.flip(frame, 1)  # 摄像头翻转
    cvimage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    pilImage = Image.fromarray(cvimage)
    pilImage = pilImage.resize((image_width, image_height), Image.LANCZOS)
    tkImage = ImageTk.PhotoImage(image=pilImage)
    return tkImage

def start_video():
    global cap
    if cap is None or not cap.isOpened():  #检查 cap 是否为 None 或未打开。如果关闭,则初始化 cap 并打开摄像头。
        cap = cv2.VideoCapture("http://192.168.4.1:81/stream")#这个是ESP32S3摄像头,我才用的是摄像头开热点的模式,这个网址可以更改,看摄像头的URL决定
    update_frame() #启动 update_frame 函数以更新视频帧。

def stop_video():
    global cap
    if cap is not None and cap.isOpened():
        cap.release() #如果打开,则释放摄像头并将 cap 置为 None。
    canvas.delete("all")  # 清除画布内容

def update_frame():
    global image_container, cap
    if cap is None or not cap.isOpened():
        return
    pic = tkImage()
    if pic:
        canvas.create_image(0, 0, anchor='nw', image=pic)
        image_container = pic  # 保存引用
    else:
        print("No image to display")
    top.after(10, update_frame)  # 每10毫秒更新一次图像

top = tk.Tk()
top.title('视频窗口')
top.geometry('900x600')
image_width = 600
image_height = 500
canvas = Canvas(top, bg='white', width=image_width, height=image_height)  # 绘制画布
Label(top, text='这是wifi摄像头画面!', font=("黑体", 14), width=20, height=1).place(x=400, y=20, anchor='nw')
Button(top, text="打开视频", command=start_video).place(x=50, y=20)
Button(top, text="关闭视频", command=stop_video).place(x=50, y=60)
canvas.place(x=150, y=50)

# 保存图像对象,以防止被垃圾回收
image_container = None

top.mainloop()

# 释放摄像头
if cap is not None:
    cap.release()
相关推荐
一个王同学2 小时前
从零到一 | CV转多模态大模型 | week09 | Minillava Refactor结合手搓和llava源码深入理解多模态大模型原理
人工智能·深度学习·机器学习·计算机视觉·改行学it
Larry_Yanan9 小时前
QML面试常见问题(一)QML中组件呈现方式的方法有哪些
开发语言·c++·qt·ui·面试
Adios79410 小时前
Optimal Transport Aggregation for Visual Place Recognition VPR论文阅读
论文阅读·计算机视觉
测试员周周11 小时前
【Appium 系列】第12节-智能路由 — API测试 vs UI 测试的自动选择
开发语言·人工智能·python·功能测试·ui·appium·测试用例
嵌入式老牛13 小时前
液晶段码(米/日字格)识别—前言
opencv·段码
BU摆烂会噶13 小时前
【LangGraph】节点内调用与状态隔离
android·人工智能·python·ui·langchain·人机交互
努力努力再努力wz13 小时前
【C++高阶数据结构系列】:时间轮定时器详解:原理分析与代码实现,带你从零手撕时间轮!(附时间轮的实现源码)
c语言·开发语言·数据结构·c++·qt·算法·ui
a flying bird13 小时前
【 LPIPS + 颜色保真 + 像素级相似度 + 生成逼真度的超分 / 图像增强】
人工智能·计算机视觉
ZC跨境爬虫14 小时前
跟着 MDN 学 HTML day_58:(构建行星数据表——HTML表格高级实战指南)
前端·javascript·ui·html·音视频
BU摆烂会噶14 小时前
【LangGraph】作为节点添加与状态共享
android·人工智能·python·ui·langchain·人机交互