【问题标题】:Tkinter Canvas wont show image on c.create_imageTkinter Canvas 不会在 c.create_image 上显示图像
【发布时间】:2020-01-01 12:50:20
【问题描述】:

我有一个画布,我需要显示一张使用cv2 的 VideoCapture 拍摄的图像,因此我将其转换为:

img = Image.fromarray(img)
img = ImageTk.PhotoImage(master=window, image=img.resize((800, 600)))

但它只是不显示。

我尝试将 photoImages 母版更改为画布,但也没有用。

def cv2tk(img, window):
    # fic the colors
    b,g,r = cv2.split(img)
    img = cv2.merge((r,g,b))

    # turn img into tkphoto
    img = Image.fromarray(img)
    imgtk = ImageTk.PhotoImage(master=window, image=img.resize((800, 600), Image.ANTIALIAS)) 
    
    # return img
    return imgtk

window = Tk()
window.geometry("800x600")

c = Canvas(window, width=800, height=600)
c.grid(row=0, column=0)

vc = cv2.VideoCapture(0)
val, frame = vc.read()
img = convert.cv2tk(frame, window)

c.create_image(0, 0, image=img)

while True:
    window.update()

我希望得到一个带有来自网络摄像头的图片的窗口,但实际上我得到了一个空白窗口。

请帮忙。

【问题讨论】:

    标签: image numpy opencv tkinter cv2


    【解决方案1】:

    现在回答可能有点晚了。但这是我正在使用的一个 sn-p。

    只要您按下 Space,就会捕获图像并将其存储在您的脚本所在的位置。同时,它也会在canvas中被读取和显示。

    import cv2
    from tkinter import *
    from PIL import Image, ImageOps
    cam = cv2.VideoCapture(0)
    cv2.namedWindow("Click Space or Escape")
    
    canvas = Canvas(width=300, height=300, bg='black')
    canvas.pack(expand=YES, fill=BOTH)
    
    img_counter = 0
    while True:
        ret, frame = cam.read()
        if not ret:
            print("failed to grab frame")
            break
        cv2.imshow("Click Space or Escape", frame)
    
        k = cv2.waitKey(1)
        if k%256 == 27:
            # Press Escape to Close
            print("Escape Pressed .. Bye")
            break
        elif k%256 == 32:
            # Press Space for Image Capture
            img_name = "{}.png".format(img_counter)
            cv2.imwrite(img_name, frame)
            print("{} written!".format(img_name))
            img_counter += 1
    
            gif1 = PhotoImage(file=img_name)
            gif1 = gif1.zoom(17) 
            gif1 = gif1.subsample(28)
            canvas.create_image(10, 10, image=gif1, anchor=NW)
            mainloop()
    cam.release()
    cv2.destroyAllWindows()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 2023-03-15
      • 2017-08-26
      • 2016-12-16
      相关资源
      最近更新 更多