gpt4 book ai didi

python - 如何在Tkinter界面中显示来自OpenCV的图像?

转载 作者:行者123 更新时间:2023-12-02 17:16:24 25 4
gpt4 key购买 nike

我正在尝试从OpenCV的VideoCapture获取的Tkinter界面中连续显示和替换图像。但是,我收到以下错误,我认为是图像nu​​mpy数组格式不正确的结果:

TypeError: unhashable type: 'numpy.ndarray'


如何将其重新格式化为可以正常显示的所有内容?下面是我的代码:
import tkinter as tk
import cv2
import numpy as np
from PIL import ImageTk, Image

main = tk.Tk()
main.title("Hole Pattern Recognition")
main.geometry("300x300")

frame = tk.Frame(main)
frame.pack()

def startScan():
global main, frame
#begins utilizing webcam for scan
cap = cv2.VideoCapture(0)
while(True):
ret,img = cap.read()
img = ImageTk.PhotoImage(img)
panel = tk.Label(main, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
ch = cv2.waitKey(1)
if ch == ord('q'):
break

cap.release()
cv2.destroyAllWindows()



startButton = tk.Button(frame,
text="Start Scan",
fg="blue",
command=startScan)

startButton.pack(side=tk.TOP)
main.mainloop()

最佳答案

首先,您需要使用PIL.Image.fromarray()将捕获的图像转换为tkinter支持的格式。
其次最好不要在主线程中使用while循环,因为它将阻塞tkinter mainloop。请改用after()

import tkinter as tk
from PIL import Image, ImageTk
import cv2

cap = None

main = tk.Tk()
main.title('Hole Pattern Recognition')
#main.geometry('300x300')

frame = tk.Frame(main)
frame.pack()

def startScan():
global cap

def scan():
ret, img = cap.read()
if ret:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
tkimg = ImageTk.PhotoImage(img)
panel.config(image=tkimg)
panel.tkimg = tkimg # save a reference to the image to avoid garbage collection
panel.after(25, scan) # change 25 to other value to adjust FPS

if cap is None:
cap = cv2.VideoCapture(0)
scan() # start the capture loop
else:
print('capture already started')

startButton = tk.Button(frame, text='Start Scan', fg='blue', command=startScan)
startButton.pack()

panel = tk.Label(main)
panel.pack()

main.mainloop()

if cap:
cap.release()

关于python - 如何在Tkinter界面中显示来自OpenCV的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64600566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com