class Two_Layout(): def __init__(self, top): self.top = top self.h = int(data_demo.window_height // 1.5) self.w = int(data_demo.window_width // 1.75) self.canvas2 = Canvas(self.top, bg='LightSkyBlue', width=self.w, height=self.h, highlightthickness=2, highlightbackground='Black') self.canvas2.place(relx=0.0, rely=0.032) Thread_data(self.Thread_()) # 放线程的 def Thread_(self): self.cap = cv2.VideoCapture(0) t = threading.Thread(target=self.windows_display()) t.start() def windows_display(self): if data_demo.display_id is True: ref, frame = self.cap.read() self.canvas2.delete('all') label = tk.Label(self.canvas2, text='未接入摄像头!', font=("黑体", 25), width=15, height=1) if ref is False: label.place(relx=0.32, rely=0.45, anchor='nw') self.cap = cv2.VideoCapture(0) else: for widget in self.canvas2.winfo_children(): widget.destroy() image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image1 = Image.fromarray(image) image2 = image1.resize((self.w, self.h), Image.ANTIALIAS) self.photo = ImageTk.PhotoImage(image=image2) self.canvas2.create_image(0, 0, image=self.photo, anchor=tk.NW) self.canvas2.update() self.canvas2.after(15, self.windows_display)这个代码为什么调用了摄像头但是只有一帧的图像
时间: 2024-02-14 19:17:42 浏览: 225
这段代码调用了摄像头并在画布上实时显示摄像头画面,但只显示了一帧的图像,原因可能是以下几点:
1. 代码中的线程部分有问题,导致无法持续读取摄像头画面。建议将线程调整为以下形式:
```python
def Thread_(self):
while True:
self.windows_display()
```
2. 摄像头读取的图像数据没有被持续保存,只展示了一帧图像。可以将读取到的图像数据保存下来,以便后续使用。修改代码如下:
```python
def windows_display(self):
if data_demo.display_id is True:
ref, frame = self.cap.read()
if ref is False:
label = tk.Label(self.canvas2, text='未接入摄像头!', font=("黑体", 25), width=15, height=1)
label.place(relx=0.32, rely=0.45, anchor='nw')
self.cap = cv2.VideoCapture(0)
else:
for widget in self.canvas2.winfo_children():
widget.destroy()
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image1 = Image.fromarray(image)
self.photo = ImageTk.PhotoImage(image=image1)
self.canvas2.create_image(0, 0, image=self.photo, anchor=tk.NW)
self.canvas2.update()
self.canvas2.after(15, self.windows_display)
```
修改后的代码中,在读取到摄像头画面时,将其转换为ImageTk.PhotoImage格式,并保存在self.photo变量中,以便后续使用。同时,在每次更新画布之前,先销毁画布上的所有控件。
阅读全文