问题
Good day, I am quite new to Python programming and I was tasked to do my own GUI with image inside my GUI. I have been doing some good progress but i was stuck when I want to insert an image into my GUI from my webcam. However, I did manage to get an image from the webcam but it has to be a different window with the GUI window.
In my GUI codes, it includes a simple code like this:
(I use range i<25 because my webcam needs warming up)
for i in range (25):
_ , frame = cap.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
i+=1
cv2.imshow("Latex Truck", cv2image)
img = cv2image
label = Label(root, image = img)
label.place(x = 300, y = 300)
Now, the problem is this. I successfully obtain the frame that I need and was able to show thanks to cv2.imshow but when I try to use the same source which is the "cv2image" in tkinter, it shows this error.
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Users\FF7_C\OneDrive\Desktop\Logo.py", line 82, in Capture
label = Label(root, image = img)
File "C:\Python34\lib\tkinter\__init__.py", line 2573, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2091, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "[[[ 49 32 22 255]
Now, logically I think I did what I needed to do which is the extract an image from the webcam which I did, the only problem now is I need to understand why tkinter cannot read the same information read by cv2.imshow.
Can someone guide me on this? Thank you very much! :)
回答1:
The format returned by cv2.cvtColor(...)
is of type numpy.ndarray
. You need to convert it to format recognized by tkinter by using Pillow
module:
from tkinter import *
from PIL import Image, ImageTk
import cv2
root = Tk()
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
# convert to image format recognized by tkinter
img = Image.fromarray(img)
tkimg = ImageTk.PhotoImage(image=img)
Label(root, image=tkimg).pack()
root.mainloop()
来源:https://stackoverflow.com/questions/54068536/what-is-the-data-format-read-by-the-function-cv2-imread-working-with-tkinter-an