opencv+tkinter来在GUI内读取视频或摄像头

在TK中读取视频,主要是使用tkinter中的tkinter.after这个函数,相当于一个定时器。
当然使用threading多线程也是能够达到同样的效果

video=cv2.VideoCapture(0)
def imshow():
    global video
    global root
    global image
    res,img=video.read()

    if res==True:
        #将adarray转化为image
        img = Image.fromarray(img)
        #显示图片到label
        img = ImageTk.PhotoImage(img)
        image.image=img
        image['image']=img
    #创建一个定时器,每10ms进入一次函数
    root.after(10,imshow)

在这个函数内加上root.after相当于一个定时器每10ms进入这个函数一次,这样达到不断读取video视频的值,然后将opencv读取的ndarray类型改变为image类型再在组件中显示就行,好处是有opencv的加持可以在每次都进行图像处理。
如果需要读取视频只需要把video=cv2.VideoCapture(0)
更改为:

video=cv2.VideoCapture(video_path)
#video_path就是视频的地址

然后看完整代码:

import cv2
from PIL import Image,ImageTk
import tkinter


#创建一个TK界面
root = tkinter.Tk()
root.geometry("640x480")
root.resizable(False, False)
root.title('video')

video=cv2.VideoCapture(0)


def imshow():
    global video
    global root
    global image
    res,img=video.read()

    if res==True:
        #将adarray转化为image
        img = Image.fromarray(img)
        #显示图片到label
        img = ImageTk.PhotoImage(img)
        image.image=img
        image['image']=img
    #创建一个定时器,每10ms进入一次函数
    root.after(10,imshow)

#创建label标签
image = tkinter.Label(root, text=' ', width=640, height=480)
image.place(x=0, y=0, width=640, height=480)

imshow()

root.mainloop()

#释放video资源
video.release()

运行效果:
在这里插入图片描述
附上多线程的方法:

import cv2
import numpy as np
from PIL import Image,ImageTk
import tkinter
import threading

#创建一个TK界面
root = tkinter.Tk()
root.geometry("640x480")
root.resizable(False, False)
root.title('video')
video=cv2.VideoCapture(0,cv2.CAP_DSHOW)

def imshow():
    global video
    global image
    while True:
        res,img=video.read()
        if np.any(img):
            #将adarray转化为image
            img = Image.fromarray(img)
            #显示图片到label
            newimg = ImageTk.PhotoImage(img)
            image.image=newimg
            image['image']=newimg


#创建一个线程
t1=threading.Thread(target=imshow)
#设置线程为守护线程
t1.daemon=True

#创建label标签
image = tkinter.Label(root, text='', width=640, height=480)
image.place(x=0, y=0, width=640, height=480)

#开启线程
t1.start()

root.mainloop()


video.release()
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月明Mo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值