首页 > 解决方案 > 将 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()

标签: pythontkinter

解决方案


推荐阅读