Skip to content

Instantly share code, notes, and snippets.

@davidedelpapa
Created May 26, 2020 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidedelpapa/2c9a0d2a3e0eada5782aeda93a90c0fa to your computer and use it in GitHub Desktop.
Save davidedelpapa/2c9a0d2a3e0eada5782aeda93a90c0fa to your computer and use it in GitHub Desktop.
Tkinter, Pillow, opencv, and gPhotoSpy to view a video from Google Photos in a Tk canvas
import PIL.ImageTk
import PIL.Image
import time
import cv2
import tkinter
class ImgVideoCapture:
def __init__(self, video_url):
# gets the video from the url as a VideoCapture wrapper
self.vid = cv2.VideoCapture(video_url)
if not self.vid.isOpened():
raise Exception("Unable to open media URL", video_url)
def __del__(self):
if self.vid.isOpened():
self.vid.release()
def get_frame(self):
if self.vid.isOpened():
success, frame = self.vid.read()
if success:
# Returns the current frame converted to RGB
return (success, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
# If could't get the frame return success=False, and None image
return (False, None)
class VideoApp:
def __init__(self,
window,
video_source,
window_title="Google Photos videos through Tk and cv2"):
self.window = window
self.window.title(window_title)
self.video_url = video_source.get_url()
(self.width, self.height) = video_source.dimensions(800, 600)
self.vid = ImgVideoCapture(self.video_url)
# Create and pack a canvas
self.canvas = tkinter.Canvas(
window, width=self.width + 20, height=self.height + 20, bg='black')
self.canvas.pack(side='top', fill='both', expand='yes')
self.delay = 15 # should be according to framerate
self.update() # sets the periodoc update
self.window.mainloop() # the main loop is given to it
def update(self):
# Get a frame from the video source, and a bool for success
success, frame = self.vid.get_frame()
# If the frame was obtained set it as image in the canvas
if success:
img = PIL.Image.fromarray(frame)
img.resize((self.width, self.height), PIL.Image.ANTIALIAS)
self.single_frame = PIL.ImageTk.PhotoImage(
image=img)
self.canvas.create_image(
10, 10, image=self.single_frame, anchor='nw')
# calls itself again every self.delay milliseconds
# this effectively creates the video effect
self.window.after(self.delay, self.update)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment