python - 将 OpenCV 的帧移动到 Tkinter 时 Python 中的内存错误和属性错误
问题描述
我试图将 OpenCV 的框架移动到 Tkinter
代码如下...
import tkinter as tk
import time
from PIL import ImageTk, Image
from cv2 import cv2
显示视频
class CamWindow:
def __init__(self, window, title:str, cam_plug = 0, delay = 15):
self.delay = delay
self.window = window
self.title = title
self.window.title(self.title)
self.cam = MyVideoCapture(cam_plug)
self.canvas = tk.Canvas(self.window, width = self.cam.width, height = self.cam.height)
self.canvas.pack()
self.photoButton = tk.Button(self.window, text="SnapShot", width=30, command=self.shot)
self.photoButton.pack(anchor=tk.CENTER, expand=True)
self.update()
self.window.mainloop()
def shot(self):
ret, frame = self.cam.getPic()
if ret:
cv2.imwrite(time.strftime("%d-%m-%Y-%H-%M-%S")+".jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
def update(self):
ret, frame = self.cam.getPic()
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, cam_plug = 0):
self.cam = cv2.VideoCapture(cam_plug, cv2.CAP_DSHOW)
if not self.cam.isOpened():
raise ValueError("cannot open camera at %d", cam_plug)
self.width = self.cam.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.cam.get(cv2.CAP_PROP_FRAME_HEIGHT)
def getPic(self):
if self.cam.isOpened():
ret, frame = self.cam.read()
if ret:
return ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
else:
return ret, None
else:
return None, None
def __del__(self):
if self.cam.isOpened:
self.cam.release()
终端显示内存错误,但一切似乎都说得通。
而且我遇到了“Attributeerror:'photoimage'对象没有属性'_photoimage__photo'”如果有任何方法或代码有问题请告诉我================== =======编辑============================
我的主要文件.py 是:
from module.UI import CamWindow
def main():
CamWindow(tk.Tk(), title = "camera window", delay = 30)
if __name__ == '__main__':
main()
解决方案
推荐阅读
- java - 如何删除列表中的重复对象
不使用任何集合和循环 - javascript - 单选按钮 HTML - materlizeCSS
- python-3.x - Python Pandas:将特定行的几列从一个数据帧复制到另一个具有不同名称的数据帧
- javascript - 将 then 附加到调用堆栈中的多层承诺的最佳解决方案是什么?
- python - TensorFlow/Keras - 预期 global_average_pooling2d_1_input 的形状为 (1, 1, 2048) 但得到的数组形状为 (7, 7, 2048)
- javascript - 从高阶函数返回数组
- python - 过滤时如何考虑dataFrame中的其他行?
- ios - 导航 pushViewController 不起作用
- r - 如何使用 R 中的官员包将表格添加到 Word 文档的标题?
- python-2.7 - 如何将子文件夹模块 python 导入另一个文件?