image - Tkinter Canvas不会在c.create_image上显示图像

标签 image numpy opencv tkinter cv2

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

img = Image.fromarray(img)
img = ImageTk.PhotoImage(master=window, image=img.resize((800, 600)))
但它没有显示。
我尝试将photoImages母版更改为 Canvas ,但也无法正常工作。
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()
我希望从网络摄像头中获得一个带有图片的窗口,但实际上我得到了一个空白窗口。
请帮忙。

最佳答案

回答可能有点晚了。但是这是我正在使用的代码段。
按下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()

关于image - Tkinter Canvas不会在c.create_image上显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689924/

相关文章:

python-3.x - cv2.error : OpenCV(4. 0.0) (-215 :Assertion failed) ! _src.empty() 在函数 'cv::cvtColor' 中

css - Bootstrap 圆形响应图像未调整到相同的圆圈大小

python - Pandas Groupby 并使用自定义值创建新列

python - Numpy 温度计编码

android - 未定义对 'cv::CascadeClassifier::detectMultiScale' 的引用,但其他库链接正确

opencv - 使用OpenCV进行手语翻译

ios - CALayer 的内容中心无法快速工作

python - 如何在OpenCV的同一窗口中显示2个不同的源?

android - 捕获的图像未显示在图库中,但已成功存储在 SD 卡中

python - 创建多维数组的函数