Python GUI application to record a video using Tkinter GUI module and openCV computer vision library














































Python GUI application to record a video using Tkinter GUI module and openCV computer vision library



Program Description:

Python Program to record a video using openCV's videowriter() and a widget is designed to contain the video canvas using python's Tkinter GUI module.

Source code/Program: 

import tkinter as tk
import cv2
import PIL.Image, PIL.ImageTk
import time
import datetime as dt
import argparse

class App:
def __init__(self, window, window_title, video_source=0):
self.window = window
self.window.title(window_title)
self.video_source = video_source
self.ok=
False

#timer
self.timer=ElapsedTimeClock(self.window)

# open video source (by default this will try to open the computer webcam)
self.vid = VideoCapture(self.video_source)

# Create a canvas that can fit the above video source size
self.canvas = tk.Canvas(window, width = self.vid.width, height = self.vid.height)
self.canvas.pack()

# Button that lets the user take a snapshot
self.btn_snapshot=tk.Button(window, text=
"Snapshot", command=self.snapshot)
self.btn_snapshot.pack(side=tk.LEFT)

#video control buttons

self.btn_start=tk.Button(window, text=
'START', command=self.open_camera)
self.btn_start.pack(side=tk.LEFT)

self.btn_stop=tk.Button(window, text=
'STOP', command=self.close_camera)
self.btn_stop.pack(side=tk.LEFT)

# quit button
self.btn_quit=tk.Button(window, text=
'QUIT', command=quit)
self.btn_quit.pack(side=tk.LEFT)

# After it is called once, the update method will be automatically called every delay milliseconds
self.delay=
10
self.update()

self.window.mainloop()

def snapshot(self):
# Get a frame from the video source
ret,frame=self.vid.get_frame()

if ret:
cv2.imwrite(
"frame-"+time.strftime("%d-%m-%Y-%H-%M-%S")+".jpg",cv2.cvtColor(frame,cv2.COLOR_RGB2BGR))

def open_camera(self):
self.ok =
True
self.timer.start()
print(
"camera opened => Recording")



def close_camera(self):
self.ok =
False
self.timer.stop()
print(
"camera closed => Not Recording")


def update(self):

# Get a frame from the video source
ret, frame = self.vid.get_frame()
if self.ok:
self.vid.out.write(cv2.cvtColor(frame,cv2.COLOR_RGB2BGR))

if ret:
self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
self.canvas.create_image(
0, 0, image = self.photo, anchor = tk.NW)
self.window.after(self.delay,self.update)


class VideoCapture:
def __init__(self, video_source=0):
# Open the video source
self.vid = cv2.VideoCapture(video_source)
if not self.vid.isOpened():
raise ValueError("Unable to open video source", video_source)

# Command Line Parser
args=CommandLineParser().args


#create videowriter

# 1. Video Type
VIDEO_TYPE = {
'avi': cv2.VideoWriter_fourcc(*'XVID'),
#'mp4': cv2.VideoWriter_fourcc(*'H264'),
'mp4': cv2.VideoWriter_fourcc(*'XVID'),
}

self.fourcc=VIDEO_TYPE[args.type[
0]]

# 2. Video Dimension
STD_DIMENSIONS = {
'480p': (640, 480),
'720p': (1280, 720),
'1080p': (1920, 1080),
'4k': (3840, 2160),
}
res=STD_DIMENSIONS[args.res[
0]]
print(args.name,self.fourcc,res)
self.out = cv2.VideoWriter(args.name[
0]+'.'+args.type[0],self.fourcc,10,res)

#set video sourec width and height
self.vid.set(
3,res[0])
self.vid.set(
4,res[1])

# Get video source width and height
self.width,self.height=res


# To get frames
def get_frame(self):
if self.vid.isOpened():
ret, frame = self.vid.read()
if ret:
# Return a boolean success flag and the current frame converted to BGR
return (ret, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
else:
return (ret, None)
else:
return (ret, None)

# Release the video source when the object is destroyed
def __del__(self):
if self.vid.isOpened():
self.vid.release()
self.out.release()
cv2.destroyAllWindows()


class ElapsedTimeClock:
def __init__(self,window):
self.T=tk.Label(window,text=
'00:00:00',font=('times', 20, 'bold'), bg='green')
self.T.pack(fill=tk.BOTH, expand=
1)
self.elapsedTime=dt.datetime(
1,1,1)
self.running=
0
self.lastTime=
''
t = time.localtime()
self.zeroTime = dt.timedelta(hours=t[
3], minutes=t[4], seconds=t[5])
# self.tick()


def tick(self):
# get the current local time from the PC
self.now = dt.datetime(
1, 1, 1).now()
self.elapsedTime = self.now - self.zeroTime
self.time2 = self.elapsedTime.strftime(
'%H:%M:%S')
# if time string has changed, update it
if self.time2 != self.lastTime:
self.lastTime = self.time2
self.T.config(text=self.time2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
self.updwin=self.T.after(
100, self.tick)


def start(self):
if not self.running:
self.zeroTime=dt.datetime(
1, 1, 1).now()-self.elapsedTime
self.tick()
self.running=
1

def stop(self):
if self.running:
self.T.after_cancel(self.updwin)
self.elapsedTime=dt.datetime(
1, 1, 1).now()-self.zeroTime
self.time2=self.elapsedTime
self.running=
0


class CommandLineParser:

def __init__(self):

# Create object of the Argument Parser
parser=argparse.ArgumentParser(description=
'Script to record videos')

# Create a group for requirement
# for now no required arguments
# required_arguments=parser.add_argument_group('Required command line arguments')

# Only values is supporting for the tag --type. So nargs will be '1' to get
parser.add_argument(
'--type', nargs=1, default=['avi'], type=str, help='Type of the video output: for now we have only AVI & MP4')

# Only one values are going to accept for the tag --res. So nargs will be '1'
parser.add_argument(
'--res', nargs=1, default=['480p'], type=str, help='Resolution of the video output: for now we have 480p, 720p, 1080p & 4k')

# Only one values are going to accept for the tag --name. So nargs will be '1'
parser.add_argument(
'--name', nargs=1, default=['output'], type=str, help='Enter Output video title/name')

# Parse the arguments and get all the values in the form of namespace.
# Here args is of namespace and values will be accessed through tag names
self.args = parser.parse_args()



def main():
# Create a window and pass it to the Application object
App(tk.Tk(),
'Video Recorder')

main()


Program Explanation:

1. Run the Program in terminal/command prompt along with command-line arguments. Use -h 
for help.
2. If you run without any argument, it will run with default settings.
3. After running a GUI/widget will pop-up as shown below.
4. In GUI you can see a timer and three buttons viz. START, STOP and SNAPSHOT.
5. You can press the START button to start a video recording.
6. You can press the STOP button to stop the video recording.
7. You can press the SNAPSHOT button to take a snapshot of the current frame.

Output:


The recorded file will be saved as output.avi in the same folder as of source code's,  for default setting which you can change with the help of command-line arguments.

More Articles of Anurag Jain:

Name Views Likes
Python Program to Remove the Duplicate Items from a List 770 10
Python Program to Construct a Tree & Perform Insertion, Deletion, Display 790 0
Python Program to Count Number of Leaf Node in a Tree 1485 0
Python Program to Create a Mirror Copy of a Tree and Display using BFS Traversal 920 0
Python GUI application to record a video using Tkinter GUI module and openCV computer vision library 7114 0
Python Program to Find the Number of Nodes in a Binary Tree 830 0
Python Program to Add a Key-Value Pair to the Dictionary 725 0
Python Program to Map Two Lists into a Dictionary 969 0
Python Program for Depth First Binary Tree Search using Recursion 853 0
Python program to get disk name and its vendor from Linux/UNIX like system and return in a dictionary like structure 834 0
Python Program for face Detection using openCV and haar-cascades 1480 0
Python Program to Implement Introsort 1107 0
Python Program to Find the Largest value in a Tree using Inorder Traversal 702 0
Python Program to Print all Integers that are not Divisible by Either 2 or 3 and Lie between 1 and 50 1368 23
Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x) 1056 0
Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat 1446 10
Python Program to Implement Radix Sort 1206 0
Python Program to Print Border of given Tree in Anticlockwise Direction 819 0
Python Program to Print all Numbers in a Range Divisible by a Given Number 987 17
Python Program to Remove All Tuples in a List of Tuples with the USN Outside the Given Range 1132 0
Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches 879 13
Python Program to Find Nth Node in the Inorder Traversal of a Tree 1055 0
Python Program to Construct a B Tree 5639 0
Python Program to Implement Depth First Search Traversal using Post Order 980 0
Python Program to Sum All the Items in a Dictionary 960 0
Python Program to Check if a Number is a Perfect Number 930 15
Python Program to Build Binary Tree if Inorder or Postorder Traversal as Input 1146 0
Python Program to Form a Dictionary from an Object of a Class 959 0
Python Program to Remove the Given Key from a Dictionary 811 0
Python Program to Count Number of Non Leaf Nodes of a given Tree 788 0
Python Program to Generate Gray Codes using Recursion 960 22
Python Program to Compute Simple Interest Given all the Required Values 890 21
Python Program to Check Whether a Number is Positive or Negative 825 25
Python Program to Read a List of Words and Return the Length of the Longest One 1333 10
Python GUI application to record a video using tkinter GUI module and openCV 62 6
Python Program for Depth First Binary Tree Search without using Recursion 851 0
Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character 2473 0
Python program to get disk information, health, short test results using Smartctl one of Smartmoontools for disk analysis using Linux system 884 1
Python Program to Multiply All the Items in a Dictionary 1360 0
Python Program to Construct a Binary Search Tree and perform deletion and inorder traversal 1186 0
Python Program to Concatenate Two Dictionaries Into One 891 0
Python Program to Check if a Number is a Prime Number 764 22
Python Program to Swap the First and Last Value of a List 1105 22
Python Program to Demonstrate Circular Single Linked List 835 0
Python Program to Check if a Given Key Exists in a Dictionary or Not 775 0

Comments