Read, Write and Display video frames with OpenCV

INTRODUCTION

This article clearly focuses on read, write and display video frames with OpenCV-python. The important words for this article are OpenCV, Python and Video. We will also look into deeper about Frame Per Second, VideoCapture Object and will try to keep your interest in the article. I also suggest and request readers to have a skimmed reading of the below articles before proceeding further.

A Small Introduction to Digital Image Processing in Computer Vision

Image Processing in Computer vision: How to Read and Write Images in Python

What will be covered in this article

  1. Reading Video.
  2. Writing the Video in the new folder

Reading Video

One can define video is a sequence of fast moving images. In technical term, number of images per second is called is Frame Per Second (FPS). Let us suppose we have X FPS then one image will be displaced in 1/X seconds. Now let us connect FPS with the human brain. Around the fovea centralis (small, central pit composed of closely packed cones in the eye), the human brain processes 10 frames per second i.e 10 FPS. At 20fps, the human brain will already interpret a series of images as a moving scene. Keeping this in mind, tuning of videos in the movies or in the television is done. I hope you are getting with me. I am connecting this topic with the brain as human brain is the base for computer vision. Today technology is being researched and developed to make the machines work like human. In OpenCV, a video can be read either by using the feed from a camera connected to a computer or by reading a video file. This tutorial is about reading the video file. The first step towards reading a video file is to create a VideoCapture object. VideoCapture is a constructor is a member function of the class which initialise object of the class. It is a special member function of the class. It does not have the return type.

Prerequisite required to run the code

numpy==1.16.4
opencv-python==4.1.0.25
pkg-resources==0.0.0

Creating the virtual environment

virtualenv --python python3 **name_env**

How to install the packages

Create the requirements.txt file and copy these packages to this file and run the below command. Please activate the virtualenv before running the below code by source name_env/bin/activate

pip install -r requirements.txt

Error faced while running the above command

If readers or passionate coders face any problem while running the above command, please remove the pkg-resources==0.0.0 from the requirements.txt file.

Please see the below code for reading and displaying video frames with OpenCV

import cv2
import os
current_path = os.getcwd()
print("Show the current path", current_path)
video_join = os.path.join(current_path, 'any_video.mp4')
print("Show the joined path", video_join)
# VideoCapture is the object to read the video
cap = cv2.VideoCapture(video_join)
print("Show the value of cap.", cap)
print("Show Boolean value of video read", cap.isOpened())

# Implementing try and except condition
try:
    if (cap.isOpened()== False):
        print("Error in reading the input video")
    else:
        raise Exception
except Exception:
	while cap.isOpened():
		print("There is no error in reading the file")
			# ret is boolean value which is either true or false
			# frame is considered as an image and video is considered /
			# an sequence of fast moving images
		ret, frame = cap.read()
		print("show the value of ret", ret)
			# if condition is true
		if ret == True:
	    # show the frame which is image in the video
			cv2.imshow('Frame',frame)
		    # if you put the value of waitKey(0), you have to wait for infinite time /
		    # Once you press q key the condition will break
			if cv2.waitKey(25) & 0xFF == ord('q'):
				break
			# exit()
			# # if value of ret is not true then break from the loop
		else:
			break
# release cap after reading the file
	cap.release()
# destroy frames after completion of the process
	cv2.destroyAllWindows()

Writing the Video in the new folder

I hope readers and passionate coders have been successful in completing the task 1. Now let us move towards task 2 to write the video frames to the new folder. Please have a look at the code to understand the things in a better way.

import cv2
import os
current_path = os.getcwd()
print("Show the current path", current_path)
video_join = os.path.join(current_path, 'any_video.mp4')
print("Show the joined path", video_join)
# VideoCapture is the object to read the video
cap = cv2.VideoCapture(video_join)
print("Show the value of cap.", cap)

print("Show Boolean value of video read", cap.isOpened())
# Implementing try and except condition
try:

    if (cap.isOpened()== False):
        print("Error in reading the input video")
    else:
        raise Exception


except Exception:
# if everything goes well, flow of the code will go here and
    # frame width and height is being calculated
		frame_width = int(cap.get(3))
		frame_height = int(cap.get(4))
		print("Show frame width.", frame_width)


		# defining  the output folder where to save the file
		if not os.path.exists('out_folder'):
			os.makedirs('out_folder')
		else:
			print("Folder already exists")
		
		out_put_file = os.path.join(current_path, 'out_folder', 'outpy.avi')
		print("Show the name of the output file where video is to be written:", 
								out_put_file)
		# M-JPEG or MJPEG) as a video compression format
		fourcc = cv2.VideoWriter_fourcc(*'MJPG')						
		out = cv2.VideoWriter(out_put_file,fourcc, 
								10.0, (frame_width,frame_height))
		
		while cap.isOpened():
			print("There is no error in reading the file")
				# ret is boolean value which is either true or false
				# frame is considered as an image and video is considered /
				# an sequence of fast moving images
			ret, frame = cap.read()
			print("show the value of ret", ret)
				# if condition is true
			if ret == True:
				# print(frame)
			# show the frame which is image in the video
				
				cv2.imshow('Frame',frame)
				out.write(frame)
				# if you put the value of waitKey(0), you have to wait for infinite time /
				# Once you press q key the condition will break
				if cv2.waitKey(25) & 0xFF == ord('q'):
					break
				# exit()
				# # if value of ret is not true then break from the loop
			else:
				break
			# release cap after reading the file
			cap.release()
			# destroy frames after completion of the process
			cv2.destroyAllWindows()

Bottom-Line

In a nutshell, following summary can be concluded from this article. Video is group of images which are moving with respect to time. This is termed as FPS (Frame Per Second). Code is written using python programming language using opencv library. Practical explanation of video is provided at the start of the video along with the connection with it with brain. I except that readers have learned about something here and their confidence is boosted.  If AI Sangam have achieved this in this article, then writing is successful as we are readers oriented. I hope you have got also good knowledge by reading the articles in images which I have mentioned in the start of this article. I also request readers to go to AI Sangam You tube Channel to see some of the exciting and new trending videos to cope with the competitive IT Industry. Please stay with us through our AI Sangam Facebook page as well as you can email us at aisangamofficial@gmail.com

Leave a Reply

Your email address will not be published.