OpenCV-Python TutorialsDocumentationRelease betaeastWillowNov 09, 2017

Contents12OpenCV-Python Tutorials1.1 Introduction to OpenCV . . . . . . . . . .1.2 Gui Features in OpenCV . . . . . . . . . .1.3 Core Operations . . . . . . . . . . . . . .1.4 Image Processing in OpenCV . . . . . . .1.5 Feature Detection and Description . . . . .1.6 Video Analysis . . . . . . . . . . . . . . .1.7 Camera Calibration and 3D Reconstruction1.8 Machine Learning . . . . . . . . . . . . .1.9 Computational Photography . . . . . . . .1.10 Object Detection . . . . . . . . . . . . . .1.11 OpenCV-Python Bindings . . . . . . . . .Indices and tables.36193446154190208226251260265269i


OpenCV-Python Tutorials Documentation, Release betaThis is Fork -TutorialsBut It updated in 2013 , Too Old. So I Made thisUpdate Date:8 Jul 2016Contents:Contents1

OpenCV-Python Tutorials Documentation, Release beta2Contents

CHAPTER1OpenCV-Python Tutorials Introduction to OpenCVLearn how to setup OpenCV-Python on your computer! Gui Features in OpenCVHere you will learn how to display and save images and videos, controlmouse events and create trackbar. Core OperationsIn this section you will learn basic operations on image like pixel editing,geometric transformations, code optimization, some mathematical tools etc. Image Processing in OpenCV3

OpenCV-Python Tutorials Documentation, Release betaIn this section you will learn different image processing functions insideOpenCV. Feature Detection and DescriptionIn this section you will learn about feature detectors and descriptors Video AnalysisIn this section you will learn different techniques to work with videos likeobject tracking etc. Camera Calibration and 3D ReconstructionIn this section we will learn about camera calibration, stereo imaging etc. Machine LearningIn this section you will learn different image processing functions insideOpenCV. Computational PhotographyIn this section you will learn different computational photography techniques like image denoising etc. Object Detection4Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release betaIn this section you will object detection techniques like face detection etc. OpenCV-Python BindingsIn this section, we will see how OpenCV-Python bindings are generated5

OpenCV-Python Tutorials Documentation, Release beta1.1 Introduction to OpenCV Introduction to OpenCV-Python TutorialsGetting Started with OpenCV-Python Install OpenCV-Python in WindowsSet Up OpenCV-Python in Windows Install OpenCV-Python in FedoraSet Up OpenCV-Python in Fedora6Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta1.1.1 Introduction to OpenCV-Python TutorialsOpenCVOpenCV was started at Intel in 1999 by Gary Bradsky and the first release came out in 2000. Vadim Pisarevskyjoined Gary Bradsky to manage Intel’s Russian software OpenCV team. In 2005, OpenCV was used on Stanley, thevehicle who won 2005 DARPA Grand Challenge. Later its active development continued under the support of WillowGarage, with Gary Bradsky and Vadim Pisarevsky leading the project. Right now, OpenCV supports a lot of algorithmsrelated to Computer Vision and Machine Learning and it is expanding day-by-day.Currently OpenCV supports a wide variety of programming languages like C , Python, Java etc and is available ondifferent platforms including Windows, Linux, OS X, Android, iOS etc. Also, interfaces based on CUDA and OpenCLare also under active development for high-speed GPU operations.OpenCV-Python is the Python API of OpenCV. It combines the best qualities of OpenCV C API and Pythonlanguage.OpenCV-PythonPython is a general purpose programming language started by Guido van Rossum, which became very popular inshort time mainly because of its simplicity and code readability. It enables the programmer to express his ideas infewer lines of code without reducing any readability.Compared to other languages like C/C , Python is slower. But another important feature of Python is that it canbe easily extended with C/C . This feature helps us to write computationally intensive codes in C/C and createa Python wrapper for it so that we can use these wrappers as Python modules. This gives us two advantages: first,our code is as fast as original C/C code (since it is the actual C code working in background) and second, itis very easy to code in Python. This is how OpenCV-Python works, it is a Python wrapper around original C implementation.And the support of Numpy makes the task more easier. Numpy is a highly optimized library for numerical operations.It gives a MATLAB-style syntax. All the OpenCV array structures are converted to-and-from Numpy arrays. Sowhatever operations you can do in Numpy, you can combine it with OpenCV, which increases number of weapons inyour arsenal. Besides that, several other libraries like SciPy, Matplotlib which supports Numpy can be used with this.So OpenCV-Python is an appropriate tool for fast prototyping of computer vision problems.OpenCV-Python TutorialsOpenCV introduces a new set of tutorials which will guide you through various functions available in OpenCV-Python.This guide is mainly focused on OpenCV 3.x version (although most of the tutorials will work with OpenCV 2.xalso).A prior knowledge on Python and Numpy is required before starting because they won’t be covered in this guide.Especially, a good knowledge on Numpy is must to write optimized codes in OpenCV-Python.This tutorial has been started by Abid Rahman K. as part of Google Summer of Code 2013 program, under the guidanceof Alexander Mordvintsev.OpenCV Needs You !!!Since OpenCV is an open source initiative, all are welcome to make contributions to this library. And it is same forthis tutorial also.So, if you find any mistake in this tutorial (whether it be a small spelling mistake or a big error in code or concepts,whatever), feel free to correct it.1.1. Introduction to OpenCV7

OpenCV-Python Tutorials Documentation, Release betaAnd that will be a good task for freshers who begin to contribute to open source projects. Just fork the OpenCVin github, make necessary corrections and send a pull request to OpenCV. OpenCV developers will check your pullrequest, give you important feedback and once it passes the approval of the reviewer, it will be merged to OpenCV.Then you become a open source contributor. Similar is the case with other tutorials, documentation etc.As new modules are added to OpenCV-Python, this tutorial will have to be expanded. So those who knows aboutparticular algorithm can write up a tutorial which includes a basic theory of the algorithm and a code showing basicusage of the algorithm and submit it to OpenCV.Remember, we together can make this project a great success !!!ContributorsBelow is the list of contributors who submitted tutorials to OpenCV-Python.1. Alexander Mordvintsev (GSoC-2013 mentor)2. Abid Rahman K. (GSoC-2013 intern)Additional Resources1. A Quick guide to Python - A Byte of Python2. Basic Numpy Tutorials3. Numpy Examples List4. OpenCV Documentation5. OpenCV Forum1.1.2 Install OpenCV-Python in WindowsGoalsIn this tutorial We will learn to setup OpenCV-Python in your Windows system.Below steps are tested in a Windows 7-64 bit machine with Visual Studio 2010 and Visual Studio 2012. The screenshotsshows VS2012.Installing OpenCV from prebuilt binaries1. Below Python packages are to be downloaded and installed to their default locations.1.1. Python-2.7.x.1.2. Numpy.1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).2. Install all packages into their default locations. Python will be installed to C:/Python27/.3. After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.4. Download latest OpenCV release from sourceforge site and double-click to extract it.7. Goto opencv/build/python/2.7 folder.8Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta8. Copy cv2.pyd to C:/Python27/lib/site-packeges.9. Open Python IDLE and type following codes in Python terminal. import cv2 print cv2. versionIf the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.Building OpenCV from source1. Download and install Visual Studio and CMake.1.1. Visual Studio 20121.2. CMake2. Download and install necessary Python packages to their default locations2.1. Python 2.7.x2.2. Numpy2.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials.)Note: In this case, we are using 32-bit binaries of Python packages. But if you want to use OpenCV for x64, 64-bitbinaries of Python packages are to be installed. Problem is that, there is no official 64-bit binaries of Numpy. Youhave to build it on your own. For that, you have to use the same compiler used to build Python. When you start PythonIDLE, it shows the compiler details. You can get more information here. So your system must have the same VisualStudio version and build Numpy from source.Note: Another method to have 64-bit Python packages is to use ready-made Python distributions from third-partieslike Anaconda, Enthought etc. It will be bigger in size, but will have everything you need. Everything in a single shell.You can also download 32-bit versions also.3. Make sure Python and Numpy are working fine.4. Download OpenCV source. It can be from Sourceforge (for official release version) or from Github (for latestsource).5. Extract it to a folder, opencv and create a new folder build in it.6. Open CMake-gui (Start All Programs CMake-gui)7. Fill the fields as follows (see the image below):7.1. Click on Browse Source. and locate the opencv folder.7.2. Click on Browse Build. and locate the build folder we created.7.3. Click on Configure.1.1. Introduction to OpenCV9

OpenCV-Python Tutorials Documentation, Release beta7.4. It will open a new window to select the compiler. Choose appropriate compiler (here, VisualStudio 11) and click Finish.7.5. Wait until analysis is finished.8. You will see all the fields are marked in red. Click on the WITH field to expand it. It decides what extra featuresyou need. So mark appropriate fields. See the below image:10Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta9. Now click on BUILD field to expand it. First few fields configure the build method. See the below image:1.1. Introduction to OpenCV11

OpenCV-Python Tutorials Documentation, Release beta10. Remaining fields specify what modules are to be built. Since GPU modules are not yet supported by OpenCVPython, you can completely avoid it to save time (But if you work with them, keep it there). See the imagebelow:12Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta11. Now click on ENABLE field to expand it. Make sure ENABLE SOLUTION FOLDERS is unchecked (Solution folders are not supported by Visual Studio Express edition). See the image below:1.1. Introduction to OpenCV13

OpenCV-Python Tutorials Documentation, Release beta12. Also make sure that in the PYTHON field, everything is filled. (Ignore PYTHON DEBUG LIBRARY). Seeimage below:13. Finally click the Generate button.14. Now go to our opencv/build folder. There you will find OpenCV.sln file. Open it with Visual Studio.15. Check build mode as Release instead of Debug.16. In the solution explorer, right-click on the Solution (or ALL BUILD) and build it. It will take some time tofinish.17. Again, right-click on INSTALL and build it. Now OpenCV-Python will be installed.14Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta18. Open Python IDLE and enter import cv2. If no error, it is installed correctly.Note: We have installed with no other support like TBB, Eigen, Qt, Documentation etc. It would be difficult toexplain it here. A more detailed video will be added soon or you can just hack around.Additional ResourcesExercises1. If you have a windows machine, compile the OpenCV from source. Do all kinds of hacks. If you meet anyproblem, visit OpenCV forum and explain your problem.1.1.3 Install OpenCV-Python in FedoraGoalsIn this tutorial We will learn to setup OpenCV-Python in your Fedora system. Below steps are tested for Fedora 18(64-bit) and Fedora 19 (32-bit).IntroductionOpenCV-Python can be installed in Fedora in two ways, 1) Install from pre-built binaries available in fedora repositories, 2) Compile from the source. In this section, we will see both.Another important thing is the additional libraries required. OpenCV-Python requires only Numpy (in addition toother dependencies, which we will see later). But in this tutorials, we also use Matplotlib for some easy and niceplotting purposes (which I feel much better compared to OpenCV). Matplotlib is optional, but highly recommended.Similarly we will also see IPython, an Interactive Python Terminal, which is also highly recommended.Installing OpenCV-Python from Pre-built BinariesInstall all packages with following command in terminal as root. yum install numpy opencv*Open Python IDLE (or IPython) and type following codes in Python terminal. import cv2 print cv2. versionIf the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.It is quite easy. But there is a problem with this. Yum repositories may not contain the latest version of OpenCValways. For example, at the time of writing this tutorial, yum repository contains 2.4.5 while latest OpenCV version is2.4.6. With respect to Python API, latest version will always contain much better support. Also, there may be chanceof problems with camera support, video playback etc depending upon the drivers, ffmpeg, gstreamer packages presentetc.So my personnel preference is next method, i.e. compiling from source. Also at some point of time, if you want tocontribute to OpenCV, you will need this.1.1. Introduction to OpenCV15

OpenCV-Python Tutorials Documentation, Release betaInstalling OpenCV from sourceCompiling from source may seem a little complicated at first, but once you succeeded in it, there is nothing complicated.First we will install some dependencies. Some are compulsory, some are optional. Optional dependencies, you canleave if you don’t want.Compulsory DependenciesWe need CMake to configure the installation, GCC for compilation, Python-devel and Numpy for creating Pythonextensions etc.yum install cmakeyum install python-devel numpyyum install gcc gcc-c Next we need GTK support for GUI features, Camera support (libdc1394, libv4l), Media Support (ffmpeg, lffmpeg-develgstreamer-plugins-base-develOptional DependenciesAbove dependencies are sufficient to install OpenCV in your fedora machine. But depending upon your requirements,you may need some extra dependencies. A list of such optional dependencies are given below. You can either leave itor install it, your call :)OpenCV comes with supporting files for image formats like PNG, JPEG, JPEG2000, TIFF, WebP etc. But it may bea little old. If you want to get latest libraries, you can install development files for these Several OpenCV functions are parallelized with Intel’s Threading Building Blocks (TBB). But if you want to enable it, you need to install TBB first. ( Also while configuring installation with CMake, don’t forget to pass -DWITH TBB ON. More details below.)yum install tbb-develOpenCV uses another library Eigen for optimized mathematical operations. So if you have Eigen installed in your system, you can exploit it. ( Also while configuring installation with CMake, don’t forget to pass -D WITH EIGEN ON.More details below.)yum install eigen3-devel16Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release betaIf you want to build documentation ( Yes, you can create offline version of OpenCV’s complete official documentationin your system in HTML with full search facility so that you need not access internet always if any question, and itis quite FAST!!! ), you need to install Sphinx (a documentation generation tool) and pdflatex (if you want to createa PDF version of it). ( Also while configuring installation with CMake, don’t forget to pass -D BUILD DOCS ON.More details below.)yum install python-sphinxyum install texliveDownloading OpenCVNext we have to download OpenCV. You can download the latest release of OpenCV from sourceforge site. Thenextract the folder.Or you can download latest source from OpenCV’s github repo. (If you want to contribute to OpenCV, choose this. Italways keeps your OpenCV up-to-date). For that, you need to install Git first.yum install gitgit clone will create a folder OpenCV in home directory (or the directory you specify). The cloning may take some timedepending upon your internet connection.Now open a terminal window and navigate to the downloaded OpenCV folder. Create a new build folder andnavigate to it.mkdir buildcd buildConfiguring and InstallingNow we have installed all the required dependencies, let’s install OpenCV. Installation has to be configured withCMake. It specifies which modules are to be installed, installation path, which additional libraries to be used, whetherdocumentation and examples to be compiled etc. Below command is normally used for configuration (executed frombuild folder).cmake -D CMAKE BUILD TYPE RELEASE -D CMAKE INSTALL PREFIX /usr/local .It specifies that build type is “Release Mode” and installation path is /usr/local. Observe the -D before eachoption and . at the end. In short, this is the format:cmake [-D flag ] [-D flag ] .You can specify as many flags you want, but each flag should be preceded by -D.So in this tutorial, we are installing OpenCV with TBB and Eigen support. We also build the documentation, but weexclude Performance tests and building samples. We also disable GPU related modules (since we use OpenCV-Python,we don’t need GPU related modules. It saves us some time).(All the below commands can be done in a single cmake statement, but it is split here for better understanding.) Enable TBB and Eigen support:cmake -D WITH TBB ON -D WITH EIGEN ON .1.1. Introduction to OpenCV17

OpenCV-Python Tutorials Documentation, Release beta Enable documentation and disable tests and samplescmake -D BUILD DOCS ON -D BUILD TESTS OFF -D BUILD PERF TESTS OFF -D BUILD EXAMPLES OFF . Disable all GPU related modules.cmake -D WITH OPENCL OFF -D WITH CUDA OFF -D BUILD opencv gpu OFF -D BUILD opencv gpuarithm OFF -D BUILD opencv gpubgsegm OFF -D BUILD opencv gpucodec OFF -D BUILD opencv gpufeatures2d OFF -D BUILD opencv gpufilters OFF -D BUILD opencv gpuimgproc OFF -D BUILD opencv gpulegacy OFF -D BUILD opencv gpuoptflow OFF -D BUILD opencv gpustereo OFF -D BUILD opencv gpuwarping OFF . Set installation path and build typecmake -D CMAKE BUILD TYPE RELEASE -D CMAKE INSTALL PREFIX /usr/local .Each time you enter cmake statement, it prints out the resulting configuration setup. In the final setup you got, makesure that following fields are filled (below is the some important parts of configuration I got). These fields shouldbe filled appropriately in your system also. Otherwise some problem has happened. So check if you have correctlyperformed above steps.----GUI:GTK 2.x:GThread :---------------Video I/O:DC1394 2:Other third-party libraries:Use Eigen:Use TBB:-Python:-Interpreter:-Libraries:-numpy: core/include (ver 1.7.1)-packages path:----18Documentation:Build Documentation:Sphinx:YES (ver 2.24.19)YES (ver 2.36.3)YESYESYESYESYESYESYESYESYESYESYESYES(ver .36)0.10.36)0.10.36)Using libv4l (ver 1.0.0)YES (ver 3.1.4)YES (ver 4.0 interface 6004)/usr/bin/python2 (ver 2.7.5)/lib/ (ver ython2.7/site-packagesYES/usr/bin/sphinx-build (ver 1.1.3)Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta-------PdfLaTeX compiler:Tests and samples:Tests:Performance tests:C/C Examples:/usr/bin/pdflatexNONONOMany other flags and settings are there. It is left for you for further exploration.Now you build the files using make command and install it using make install command. make installshould be executed as root.makesumake installInstallation is over. All files are installed in /usr/local/ folder. But to use it, your Python should be able to findOpenCV module. You have two options for that.1. Move the module to any folder in Python Path : Python path can be found out by entering importsys;print sys.path in Python terminal. It will print out many locations. Move /usr/local/lib/python2.7/site-packages/ to any of this folder. For example,su mv /usr/local/lib/python2.7/site-packages/ /usr/lib/python2.7/ site-packagesBut you will have to do this every time you install OpenCV.2. Add ‘‘/usr/local/lib/python2.7/site-packages‘‘ to the PYTHON PATH: It is to be done only once. Just open /.bashrc and add following line to it, then log out and come back.export PYTHONPATH hus OpenCV installation is finished. Open a terminal and try import cv2.To build the documentation, just enter following commands:make docsmake html docsThen open opencv/build/doc/ html/index.html and bookmark it in the browser.Additional ResourcesExercises1. Compile OpenCV from source in your Fedora machine.1.2 Gui Features in OpenCV Getting Started with Images1.2. Gui Features in OpenCV19

OpenCV-Python Tutorials Documentation, Release betaLearn to load an image, display it and save it back Getting Started with VideosLearn to play videos, capture videos from Camera and write it as a video Drawing Functions in OpenCVLearn to draw lines, rectangles, ellipses, circles etc with OpenCV Mouse as a Paint-BrushDraw stuffs with your mouse Trackbar as the Color PaletteCreate trackbar to control certain parameters20Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta1.2.1 Getting Started with ImagesGoals Here, you will learn how to read an image, how to display it and how to save it back You will learn these functions : cv2.imread(), cv2.imshow() , cv2.imwrite() Optionally, you will learn how to display images with MatplotlibUsing OpenCVRead an imageUse the function cv2.imread() to read an image. The image should be in the working directory or a full path of imageshould be given.Second argument is a flag which specifies the way image should be read. cv2.IMREAD COLOR : Loads a color image. Any transparency of image will be neglected. It is the defaultflag. cv2.IMREAD GRAYSCALE : Loads image in grayscale mode cv2.IMREAD UNCHANGED : Loads image as such including alpha channelNote: Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.See the code below:import numpy as npimport cv2# Load an color image in grayscaleimg cv2.imread('messi5.jpg',0)Warning: Even if the image path is wrong, it won’t throw any error, but print img will give you NoneDisplay an imageUse the function cv2.imshow() to display an image in a window. The window automatically fits to the image size.First argument is a window name which is a string. second argument is our image. You can create as many windowsas you wish, but with different window troyAllWindows()A screenshot of the window will look like this (in Fedora-Gnome machine):1.2. Gui Features in OpenCV21

OpenCV-Python Tutorials Documentation, Release betacv2.waitKey() is a keyboard binding function. Its argument is the time in milliseconds. The function waits forspecified milliseconds for any keyboard event. If you press any key in that time, the program continues. If 0 is passed,it waits indefinitely for a key stroke. It can also be set to detect specific key strokes like, if key a is pressed etc whichwe will discuss below.cv2.destroyAllWindows() simply destroys all the windows we created. If you want to destroy any specific window,use the function cv2.destroyWindow() where you pass the exact window name as the argument.Note: There is a special case where you can already create a window and load image to it later. In that case, you canspecify whether window is resizable or not. It is done with the function cv2.namedWindow(). By default, the flag iscv2.WINDOW AUTOSIZE. But if you specify flag to be cv2.WINDOW NORMAL, you can resize window. It will behelpful when image is too large in dimension and adding track bar to windows.See the code below:cv2.namedWindow('image', cv2.WINDOW stroyAllWindows()Write an imageUse the function cv2.imwrite() to save an image.First argument is the file name, second argument is the image you want to save.cv2.imwrite('messigray.png',img)This will save the image in PNG format in the working directory.22Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release betaSum it upBelow program loads an image in grayscale, displays it, save the image if you press ‘s’ and exit, or simply exit withoutsaving if you press ESC key.import numpy as npimport cv2img cv2.imread('messi5.jpg',0)cv2.imshow('image',img)k cv2.waitKey(0)if k 27:# wait for ESC key to exitcv2.destroyAllWindows()elif k ord('s'): # wait for 's' key to save and Windows()Warning: If you are using a 64-bit machine, you will have to modify k cv2.waitKey(0) line as follows :k cv2.waitKey(0) & 0xFFUsing MatplotlibMatplotlib is a plotting library for Python which gives you wide variety of plotting methods. You will see them incoming articles. Here, you will learn how to display image with Matplotlib. You can zoom images, save it etc usingMatplotlib.import numpy as npimport cv2from matplotlib import pyplot as pltimg cv2.imread('messi5.jpg',0)plt.imshow(img, cmap 'gray', interpolation 'bicubic')plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y screen-shot of the window will look like this :1.2. Gui Features in OpenCV23

OpenCV-Python Tutorials Documentation, Release betaSee also:Plenty of plotting options are available in Matplotlib. Please refer to Matplotlib docs for more details. Some, we willsee on the way.Warning: Color image loaded by OpenCV is in BGR mode. But Matplotlib displays in RGB mode. So colorimages will not be displayed correctly in Matplotlib if image is read with OpenCV. Please see the exercises formore details.Additional Resources1. Matplotlib Plotting Styles and FeaturesExercises1. There is some problem when you try to load color image in OpenCV and display it in Matplotlib. Read thisdiscussion and understand it.24Chapter 1. OpenCV-Python Tutorials

OpenCV-Python Tutorials Documentation, Release beta1.2.2 Getting Started with VideosGoal Learn to read video, display video and save video. Learn to capture from Camera and display it. You will learn these functions : cv2.VideoCapture(), cv2.VideoWriter()Capture Video from CameraOften, we have to capture live stream with camera. OpenCV provides a very simple interface to this. Let’s capture avideo from the camera (I am using the in-built webcam of my laptop), convert it into grayscale video and display it.Just a simple task to get started.To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the nameof a video file. Device index is just the number to specify which camera. Normally one camera will be connected (asin my case). So I simply pass 0 (or -1). You can select the second camera by passing 1 and so on. After that, you cancapture frame-by-frame. But at the end, don’t forget to release the capture.import numpy as npimport cv2cap cv2.VideoCapture(0)while(True):# Capture frame-by-frameret, frame Our operations on the frame come heregray cv2.cvtColor(frame, cv2.COLOR BGR2GRAY)# Display the resulting framecv2.imshow('frame',gray)if cv2.waitKey(1) & 0xFF ord('q'):break# When everything done, release the d() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of thevideo by checking this return value.Sometimes, cap may not have initialized the capture. In that case, this code shows error. You can check whether it isinitialized or not by the method cap.isOpened(). If it is True, OK. Otherwise open it using can also access some of the features of this video using cap.get(propId) method where propId is a number from0 to 18. Each number denotes a property of the video (if it is applicable to that video) and full details can be seen here:Property Identifier. Some of these values can be modified using cap.set(propId, value). Value is the new value youwant.For example, I can check the frame width and height by cap.get(3) and cap.get(4). It gives me 640x480 bydefault. But I want to modify it to 320x240. Just use ret cap.set(3,320) and ret cap.

Below is the list of contributors who submitted tutorials to OpenCV-Python. 1.Alexander Mordvintsev (GSoC-2013 mentor) 2.Abid Rahman K. (GSoC-2013 intern) Additional Resources 1.A Quick guide to Python -A Byte of Python 2.Basic Numpy Tutorials 3.Numpy Examples List 4.OpenCV Documentation 5.OpenCV Forum 1.1.2Install OpenCV-Python in Windows Goals