python tkinter Webcam實時偵測
时间: 2023-06-23 11:25:04 浏览: 205
python使用tkinter实现浮动窗口动态实时显示时钟
使用Python的Tkinter库实现Webcam实时检测需要借助第三方库OpenCV。
下面是一个示例代码,可以实现Webcam实时检测:
```python
import tkinter as tk
import cv2
from PIL import Image, ImageTk
class Application:
def __init__(self, window, video_source=0):
self.window = window
self.window.title("Webcam实时检测")
# 打开视频流
self.video_source = video_source
self.vid = MyVideoCapture(self.video_source)
# 创建一个Canvas对象用于显示视频流
self.canvas = tk.Canvas(window, width=self.vid.width, height=self.vid.height)
self.canvas.pack()
# 创建一个“开始”按钮和“停止”按钮
self.btn_start = tk.Button(window, text="开始", width=50, command=self.start)
self.btn_start.pack(anchor=tk.CENTER, expand=True)
self.btn_stop = tk.Button(window, text="停止", width=50, command=self.stop)
self.btn_stop.pack(anchor=tk.CENTER, expand=True)
self.delay = 15
self.update()
self.window.mainloop()
def start(self):
self.vid.start()
def stop(self):
self.vid.stop()
def update(self):
# 获取一帧视频
ret, frame = self.vid.get_frame()
if ret:
self.photo = ImageTk.PhotoImage(image=Image.fromarray(frame))
self.canvas.create_image(0, 0, image=self.photo, anchor=tk.NW)
self.window.after(self.delay, self.update)
class MyVideoCapture:
def __init__(self, video_source=0):
self.vid = cv2.VideoCapture(video_source)
if not self.vid.isOpened():
raise ValueError("无法打开视频流", video_source)
self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
def start(self):
if not self.vid.isOpened():
self.vid.open(self.video_source)
def stop(self):
if self.vid.isOpened():
self.vid.release()
def get_frame(self):
if self.vid.isOpened():
ret, frame = self.vid.read()
if ret:
return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
else:
return (ret, None)
else:
return (ret, None)
def __del__(self):
if self.vid.isOpened():
self.vid.release()
# 创建GUI界面
Application(tk.Tk(), video_source=0)
```
这个示例代码中,我们使用了OpenCV读取摄像头的视频流,并将每一帧转换成Tkinter支持的图像格式,然后在Canvas对象上显示。同时,我们还创建了“开始”和“停止”按钮,用于控制视频流的开启和关闭。
阅读全文