How to display the video in tkinter canvas frame by frame? - python

I am dealing with tkinter and opencv to display frames of video in tkinter canvas. my code is as following :
import tkinter as tk
from PIL import ImageTk as itk
from PIL import Image
from tkinter import filedialog as fd
import cv2
window = tk.Tk()
class window_tk():
def __init__(self,main):
self.canvas = tk.Canvas(main, bg='white' )
self.img = itk.PhotoImage(file=self.init_img_route)
self.bg= self.canvas.create_image(0,0,anchor = tk.NW,image=self.img)
self.vid = None
def load_video(self):
self.foldername = fd.askopenfilename(parent=window,initialdir="C:/",title='Select a video file to load.',filetypes=[('video files','*.wmv *.mp4 *.mov *.avi')])
self.label_foldername.config(text='Video Load : '+self.foldername)
self.current_pic_num=0
try:
self.vid = cv2.VideoCapture(self.foldername)
frame_number =0
print(self.vid,self.vid.isOpened())
self.frame_count = 0
if self.vid.isOpened():
vid_w = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
vid_h = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
vid_f = self.vid.get(cv2.CAP_PROP_FPS)
ret,frame = self.vid.read()
#cv2.imshow('frame',frame)
frame_convert = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
#print(self.frame_count, vid_w,vid_h,vid_f,frame.shape)
imgg = itk.PhotoImage(Image.fromarray(frame_convert))
self.canvas.itemconfig(self.bg, image = imgg)
self.canvas.pack(fill='both',expand=1)
# frame_number+=1
except IndexError:
pass
I confirmed that frame has successfully loaded by checking it as cv2.imshow(), but The canvas only shows the white empty image. Is there anything I missed ?

I found answer and leave the solution for my study.
I changed imgg to self.img and let it globally used in class.
I don't know why it solved the problem so if anyone can explain the reason thank you very much.

Related

How to set the speed of a gif in Python

i am using Python and I inserted a gif in my project. The issue is when i start the application the gif in the application runs in different way than orginal gif. I think that the frames in the gif are run in different speed. How to set the original gif?
I imported PIL and tkinter. This is the code:
import threading
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
def play_gif():
global img
img = Image.open("Gifs/beaming_face_with_smiling_eyes.gif")
lbl = Label(root)
lbl.place(x = 0, y = 0)
for img in ImageSequence.Iterator(img):
img = ImageTk.PhotoImage(img)
lbl.config(image = img)
root.update()
def exit():
root.destroy()
threading.Timer(3.0, play_gif).start()
Button(root,text = "exit", command=exit).place(x = 450, y = 300)
root.mainloop()

How can I remove blur / blur and rotate at the same time?

I am a beginner in python and learning about PIL and tkinter.
Now what I am trying is to edit a image and I am struggling from blur and rotate.
When I blur an image, I cannot get rid of it without rotating it. (I want to make a button to on/off blur)
And if I blur/rotate an image,
Another one doesn't work at the same time.
How can I solve this problem? here is my code
import tkinter as tk
from PIL import Image, ImageTk, ImageFilter
from tkinter import filedialog as fd
img=None
tk_img=None
angle=0
def open():
global img, tk_img
filename=fd.askopenfilename()
img=Image.open(filename)
tk_img=ImageTk.PhotoImage(img)
canvas.create_image(250,250,image=tk_img)
window.update()
def quit():
window.destroy()
def image_rotate():
global img,tk_img,angle
angle=angle+45
tk_img=ImageTk.PhotoImage(img.rotate(angle))
canvas.create_image(250,250,image=tk_img)
window.update()
def image_blur():
global img,tk_img
tk_img=ImageTk.PhotoImage(img.filter(ImageFilter.BLUR))
canvas.create_image(250,250,image=tk_img)
window.update()
window = tk.Tk() #윈도우 생성
canvas=tk.Canvas(window,width=500,height=500)
canvas.pack()
menubar = tk.Menu(window) #메뉴바 생성
filemenu = tk.Menu(menubar) #파일메뉴를 메뉴바에 달아줌
filemenu.add_command(label="picture", command=open)
filemenu.add_command(label="exit", command=quit)
menubar.add_cascade(label="파일", menu=filemenu)
imagemenu=tk.Menu(menubar)
imagemenu.add_command(label="rotate",command=image_rotate)
imagemenu.add_command(label="blur",command=image_blur)
menubar.add_cascade(label="movement", menu=imagemenu)
window.config(menu=menubar)
window.mainloop()
The reason is quite obvious, your img object as seen is only defined/updated in open(), so the image will always refer to the original image selected and not the new edited image, so to show the change store it in a new variable and then globalize it.
Also note that you are creating a new canvas image every time you call the function, which is not efficient, so make a single canvas image and then update it each time, inside the function using itemconfig() method.
def open():
global img, tk_img
filename = fd.askopenfilename()
img = Image.open(filename)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
def image_rotate():
global tk_img, angle, img
angle += 45 # More pythonic to always use += rather than a = a + 10
img = img.rotate(angle)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
angle -= 45
def image_blur():
global tk_img, img
img = img.filter(ImageFilter.BLUR)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
canvas = tk.Canvas(window,width=500,height=500)
canvas.create_image(250,250,tag='img') # Create initial canvas object
canvas.pack()
Also take a look at how I formatted your code to make it look more near, follow PEP 8 -- Style Guide for Python Code for more.
You can blur the image using opencv package
import cv2
img = cv2.imread('imagepath')
blurImg = cv2.blur(img,(10,10))
cv2.imshow('blurred image',blurImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Or u can check the documentation of opencv to blurr the image.
U can also rotate image using opencv
# importing cv2
import cv2
src = cv2.imread(path)
window_name = 'Image'
image = cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE)
# Displaying the image
cv2.imshow(window_name, image)
cv2.waitKey(0)

python 3.x tkinter, integrating frames from opencv cv2 into tkinter window

I have a question, how do I integrate tkinter with cv2, I mean I can create a tkinter window filled with objects and I can open my laptop camera in a frame, but I want to integrate this "frame" from openCV cv2 into the tkinter window, next to the other objects, How do I do that?
I am using, Python 3.4, OpenCV, Numpy, Scipy, Windows 8
here is my code
import time, serial, sys, os, cv2
import tkinter as tk
from tkinter import *
from cv2 import *
from scipy import *
from numpy import array
from tkinter import ttk
try:
import Tkinter
import ttk
except ImportError:
import tkinter as Tkinter
import tkinter.ttk as ttk
mGui = Tk()
mGui.geometry('120x67+0+0')
mGui.configure(background="Sky Blue")
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
cv2.imshow("Camera's View", frame)
mGui.mainloop()
thanks
I understand now, if you too pull me up
I have to
create a frame
create a label inside of the frame
take the camera's view and convert it into an image
read the image and assigned to a variable
create a new property for the label (image)
assign the red image to the property
configure the label to display the image
so clear now, so obvious
here is the code (include previous libraries)
from PIL import Image, ImageTk (add library)
mGui = Tk()
mGui.geometry('600x600+0+0')
mGui.configure(background="Sky Blue")
fframe = Frame(mGui, width=500, height=500)
fframe.place(x=50, y=50)
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
v1 = Label(fframe, text="fchgvjvjhb")
v1.place(x=0, y=10)
v2 = Label(fframe, text="ajajajaja")
v2.place(x=300, y=10)
def dddd():
ret, frame = cap.read()
img = Image.fromarray(frame)
nimg = ImageTk.PhotoImage(image=img)
v1.n_img = nimg
v1.configure(image=nimg)
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gimg = Image.fromarray(gray)
gnimg = ImageTk.PhotoImage(image=gimg)
v2.ng_img = gnimg
v2.configure(image=gnimg)
mGui.after(10, dddd)
dddd()
mGui.mainloop()

How do I place an image (.png) within a `LabelFrame`, and resize it, in Tkinter?

I'm trying to place a .png image within a LabelFrame in a Tkinter window. I imported PIL so .png image types should be supported (right?). I can't seem to get the image to show up.
Here is my revised code:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=150, height=150)
make_frame.pack()
stim = "image.png"
width = 100
height = 100
stim1 = stim.resize((width, height), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image.open(stim1))
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()
With this code, I got an AttributeError that reads: "'str' has no attribute 'resize'"
#Mickey,
You have to call the .resize method on the PIL.Image object and not the filename, which is a string. Also, you may prefer to use PIL.Image.thumbnail instead of PIL.Image.resize, for reasons described clearly here. Your code was close, but this might be what you need:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=100, height=100)
make_frame.pack()
stim_filename = "image.png"
# create the PIL image object:
PIL_image = Image.open(stim_filename)
width = 100
height = 100
# You may prefer to use Image.thumbnail instead
# Set use_resize to False to use Image.thumbnail
use_resize = True
if use_resize:
# Image.resize returns a new PIL.Image of the specified size
PIL_image_small = PIL_image.resize((width,height), Image.ANTIALIAS)
else:
# Image.thumbnail converts the image to a thumbnail, in place
PIL_image_small = PIL_image
PIL_image_small.thumbnail((width,height), Image.ANTIALIAS)
# now create the ImageTk PhotoImage:
img = ImageTk.PhotoImage(PIL_image_small)
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()

Resizing pictures in PIL in Tkinter

I'm currently using PIL to display images in Tkinter. I'd like to temporarily resize these images so that they can be viewed more easily. How can I go about this?
Snippet:
self.pw.pic = ImageTk.PhotoImage(Image.open(self.pic_file))
self.pw.pic_label = TK.Label(self.pw , image=self.pw.pic,borderwidth=0)
self.pw.pic_label.grid(column=0,row=0)
Here's what I do and it works pretty well...
image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) ## The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)
There you go :)
EDIT:
Here is my import statement:
from Tkinter import *
import tkFont
from PIL import Image
And here is the complete working code I adapted this example from:
im_temp = Image.open(Image_Location)
im_temp = im_temp.resize((250, 250), Image.ANTIALIAS)
im_temp.save("ArtWrk.ppm", "ppm") ## The only reason I included this was to convert
## The image into a format that Tkinter woulden't complain about
self.photo = PhotoImage(file="ArtWrk.ppm") ## Open the image as a tkinter.PhotoImage class()
self.Artwork.destroy() ## Erase the last drawn picture (in the program the picture I used was changing)
self.Artwork = Label(self.frame, image=self.photo) ## Sets the image too the label
self.Artwork.photo = self.photo ## Make the image actually display (If I don't include this it won't display an image)
self.Artwork.pack() ## Repack the image
And here are the PhotoImage class docs: http://www.pythonware.com/library/tkinter/introduction/photoimage.htm
Note...
After checking the pythonware documentation on ImageTK's PhotoImage class (Which is very sparse) I appears that if your snippet works than this should as well as long as you import the PIL "Image" Library an the PIL "ImageTK" Library and that both PIL and tkinter are up-to-date. On another side-note I can't even find the "ImageTK" module life for the life of me. Could you post your imports?
if you don't want save it you can try it:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
same = True
#n can't be zero, recommend 0.25-4
n=2
path = "../img/Stalin.jpeg"
image = Image.open(path)
[imageSizeWidth, imageSizeHeight] = image.size
newImageSizeWidth = int(imageSizeWidth*n)
if same:
newImageSizeHeight = int(imageSizeHeight*n)
else:
newImageSizeHeight = int(imageSizeHeight/n)
image = image.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image)
Canvas1 = Canvas(root)
Canvas1.create_image(newImageSizeWidth/2,newImageSizeHeight/2,image = img)
Canvas1.config(bg="blue",width = newImageSizeWidth, height = newImageSizeHeight)
Canvas1.pack(side=LEFT,expand=True,fill=BOTH)
root.mainloop()
the easiest might be to create a new image based on the original, then swap out the original with the larger copy. For that, a tk image has a copy method which lets you zoom or subsample the original image when making the copy. Unfortunately it only lets you zoom/subsample in factors of 2.

Categories

Resources