Blog

How to access video using Python Open CV?

Open CV in Python is the Open Computer Vision Library. Open CV is used for Image Processing, Video Processing, Pattern Matching, etc

Open CV is written mainly in C++, is platform independent and free to use,

Open CV  official site is at  Open CV

Open CV is available to Python users as the CV2 library.

Anaconda users can download it by writing

Open CV requires the numpy arrays and the scikit libraries as well.

So, you need to execute the following scripts on the command prompt.

pip install numpy scipy matplotlib scikit-learn jupyter
pip install opencv-contrib-python

 

Open CV github is hosted at

https://github.com/opencv/opencv

We will develop a program to open a Video Source(my laptop web camera ) and play a live video.

We start with creating an object of type VideoCapture.

Here is the code for VideoCapture

#include “opencv2/opencv.hpp”

using namespace cv;

int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;

Mat edges;
namedWindow(“edges”,1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow(“edges”, edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}

[/c++]

Video Capture

Python Constructors for VideoCapture are

Python: cv2.VideoCapture() → <VideoCapture object>
Python: cv2.VideoCapture(filename) → <VideoCapture object>
Python: cv2.VideoCapture(device) → <VideoCapture object>
C: CvCapture* cvCaptureFromCAM(int device)
Python: cv.CaptureFromCAM(index) → CvCapture

 

After getting an object of type VideoCapture we call the read method of the VideoCapture object. It returns two values.

Python: cv2.VideoCapture.read([image]) → retval, image

retval will be true or false depending on the success or failure. Will be false at the end. image will be null on end.

 

Then we need to convert the image into a desired color format.

This is done using the cvtColor method of the cv2 module.

It converts an image from one color space to another

Python: cv2.cvtColor(src, code[, dst[, dstCn]]) → dst

Python: cv.CvtColor(src, dst, code) → None
Parameters:
src – input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
dst – output image of the same size and depth as src.
code – color space conversion code (see the description below).
dstCn – number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code .

 

https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html

The possible transformations are.

RGB <=> GRAY ( CV_BGR2GRAY, CV_RGB2GRAY, CV_GRAY2BGR, CV_GRAY2RGB )

RGB <=> YCrCb JPEG (or YCC) ( CV_BGR2YCrCb, CV_RGB2YCrCb, CV_YCrCb2BGR, CV_YCrCb2RGB )

RGB <=> HSV ( CV_BGR2HSV, CV_RGB2HSV, CV_HSV2BGR, CV_HSV2RGB )

RGB <=> HLS ( CV_BGR2HLS, CV_RGB2HLS, CV_HLS2BGR, CV_HLS2RGB ).

RGB <=> CIE L*a*b* ( CV_BGR2Lab, CV_RGB2Lab, CV_Lab2BGR, CV_Lab2RGB ).

 

The imshow function displays the image

Python: cv.ShowImage(name, image) → None
Parameters:
winname – Name of the window.
image – Image to be shown.
The function imshow displays an image in the specified window. If the window was created with the CV_WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth:

If the image is 8-bit unsigned, it is displayed as is.
If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].
If the window was not created before this function, it is assumed creating a window with CV_WINDOW_AUTOSIZE.

 

imshow

 

 

waitKey

Waits for a pressed key.

Python: cv2.waitKey([delay]) → retval
Python: cv.WaitKey(delay=0) → int
Parameters: delay – Delay in milliseconds. 0 is the special value that means “forever”.
The function waitKey waits for a key event infinitely (when \texttt{delay}\leq 0 ) or for delay milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is running on your computer at that time. It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.

Wait Key

 

Python Code for displaying the video.

 


import numpy as np
import cv2 as cv

capturedevice = cv.VideoCapture(0)

while(True):

ret, image = capturedevice.read()

colorformat = cv.cvtColor(image, cv.COLOR_BGR2RGBA)

cv.imshow('My Web Camera',colorformat)
if (cv.waitKey(1) & 0xFF) == (27 & 0xFF):
break

capturedevice.release()
cv.destroyAllWindows()

&nbsp;

 

Run the program and you should see a window which will play images from your web camera. Press the escape key and the program will end.

Contact me on Whats App 

if you have any doubts or wish to learn more about Python.

I am available on Twitter.

 

Leave a Reply

Your email address will not be published. Required fields are marked *