基于opencv模块来调用笔记本摄像头,通过GUI界面,然后从视频流中获取到图像数据,并将图像数据持久化,python代码
时间: 2024-03-26 07:38:29 浏览: 17
好的,下面是基于OpenCV模块调用笔记本摄像头的Python代码,可以通过GUI界面获取视频流并将图像数据持久化到本地文件。
```python
import cv2
import tkinter as tk
from tkinter import messagebox
class CameraGUI:
def __init__(self, video_source=0):
self.cap = cv2.VideoCapture(video_source)
self.root = tk.Tk()
self.root.title("Camera GUI")
self.root.protocol('WM_DELETE_WINDOW', self.close)
self.canvas = tk.Canvas(self.root, width=self.cap.get(cv2.CAP_PROP_FRAME_WIDTH),
height=self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.canvas.pack()
self.btn_snapshot = tk.Button(self.root, text="Snapshot", command=self.snapshot)
self.btn_snapshot.pack(anchor=tk.CENTER, expand=True)
self.delay = 15
self.update()
self.root.mainloop()
def update(self):
ret, frame = self.cap.read()
if ret:
self.photo = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self.photo = cv2.resize(self.photo, (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
self.photo = self.photo.swapaxes(0, 1)
self.photo = tk.PhotoImage(data=cv2.imencode('.png', self.photo)[1].tobytes())
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
self.root.after(self.delay, self.update)
def snapshot(self):
ret, frame = self.cap.read()
if ret:
cv2.imwrite("snapshot.png", frame)
messagebox.showinfo("Snapshot", "Snapshot saved as snapshot.png")
def close(self):
self.cap.release()
self.root.destroy()
if __name__ == '__main__':
CameraGUI()
```
这段代码创建了一个名为`CameraGUI`的类,该类使用OpenCV模块调用笔记本摄像头,并在GUI界面上实时显示视频流。用户可以通过点击“Snapshot”按钮将当前帧保存为本地文件。