{"id":23005,"date":"2024-04-09T10:52:00","date_gmt":"2024-04-09T05:22:00","guid":{"rendered":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/"},"modified":"2024-09-02T17:01:32","modified_gmt":"2024-09-02T11:31:32","slug":"opencv-tutorial-in-python","status":"publish","type":"post","link":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/","title":{"rendered":"OpenCV Tutorial: A Guide to Learn OpenCV in Python"},"content":{"rendered":"\n<p>OpenCV is a widely acclaimed open-source library that provides an extensive suite of computer vision and<a href=\"https:\/\/www.mygreatlearning.com\/blog\/introduction-to-image-processing-what-is-image-processing\/\" target=\"_blank\" rel=\"noreferrer noopener\"> image processing<\/a> functions. <br><br>It offers a vast array of tools and techniques that empower developers to build cutting-edge applications in fields like robotics, augmented reality, <a href=\"https:\/\/www.mygreatlearning.com\/blog\/facial-recognition-using-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">facial recognition<\/a>, object detection, and much more. With its powerful capabilities and user-friendly interface, OpenCV has become a go-to choice for developers worldwide.<\/p>\n\n\n\n<p>In this tutorial, we will start from the basics and gradually delve into more advanced topics. We will cover everything you need to know to become proficient in OpenCV, regardless of your prior experience with <a href=\"https:\/\/www.mygreatlearning.com\/blog\/what-is-computer-vision-the-basics\/\" target=\"_blank\" rel=\"noreferrer noopener\">computer vision<\/a>. <br><br>Whether you're a beginner taking your first steps or an experienced developer looking to deepen your understanding, this guide will provide clear explanations, practical examples, and hands-on exercises to sharpen your skills.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-opencv\"><strong>What is OpenCV?<\/strong><\/h2>\n\n\n\n<p>OpenCV is an open-source software library for computer vision and machine learning. <br><br>The OpenCV full form is Open Source Computer Vision Library. It was created to provide a shared infrastructure for applications for computer vision and to speed up the use of machine perception in consumer products. OpenCV, as a BSD-licensed software, makes it simple for companies to use and change the code. <\/p>\n\n\n\n<p>Gary Bradsky invented OpenCV in 1999 and soon the first release came in 2000. This library is based on optimised C \/ C++ and supports Java and Python along with C++ through an interface. <\/p>\n\n\n\n<p>The library has more than 2500 optimised algorithms, including an extensive collection of computer vision and <a href=\"https:\/\/www.mygreatlearning.com\/blog\/most-used-machine-learning-algorithms-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">machine learning algorithms<\/a>, both classic and state-of-the-art.<\/p>\n\n\n\n<p>Using OpenCV it becomes easy to do complex tasks such as&nbsp;identify and recognise faces, identify objects, classify human actions in videos, track camera movements, track moving objects, extract 3D object models, generate 3D point clouds from stereo cameras, stitch images together to generate an entire scene with a high resolution image and many more.<\/p>\n\n\n\n<p>Let's get started!<\/p>\n\n\n\n    <div class=\"courses-cta-container\">\n        <div class=\"courses-cta-card\">\n            <div class=\"courses-cta-header\">\n                <div class=\"courses-learn-icon\"><\/div>\n                <span class=\"courses-learn-text\">Transform Healthcare with AI<\/span>\n            <\/div>\n            <p class=\"courses-cta-title\">\n                <a href=\"https:\/\/online.lifelonglearning.jhu.edu\/jhu-ai-in-healthcare-certificate-program\" class=\"courses-cta-title-link\">AI in Healthcare Program<\/a>\n            <\/p>\n            <p class=\"courses-cta-description\">Transform healthcare with AI. Apply now for Johns Hopkins AI in Healthcare Program and enhance patient outcomes with cutting-edge skills<\/p>\n            <div class=\"courses-cta-stats\">\n                <div class=\"courses-stat-item\">\n                    <div class=\"courses-stat-icon courses-user-icon\"><\/div>\n                    <span>Duration: 10 weeks<\/span>\n                <\/div>\n                <div class=\"courses-stat-item\">\n                    <div class=\"courses-stat-icon courses-star-icon\"><\/div>\n                    <span>8+ Case Studies<\/span>\n                <\/div>\n            <\/div>\n            <a href=\"https:\/\/online.lifelonglearning.jhu.edu\/jhu-ai-in-healthcare-certificate-program\" class=\"courses-cta-button\">\n                Discover the Program\n                <div class=\"courses-arrow-icon\"><\/div>\n            <\/a>\n        <\/div>\n    <\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-computer-vision\"><strong>What is Computer Vision?<\/strong><\/h2>\n\n\n\n<p>The term Computer Vision (CV) is used and heard very often in artificial intelligence (AI) and deep learning (DL) applications. The term essentially means giving a computer the ability to see the world as we humans do.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Computer Vision is a field of study which enables computers to replicate the human visual system. As already mentioned above, It\u2019s a subset of artificial intelligence which collects information from digital images or videos and processes them to define the attributes. <\/li>\n\n\n\n<li>The entire process involves image acquiring, screening, analysing, identifying and extracting information. This extensive processing helps computers to understand any visual content and act on it accordingly.&nbsp;<\/li>\n\n\n\n<li>Computer vision projects translate digital visual content into explicit descriptions to gather multi-dimensional data. This data is then turned into a computer-readable language to aid the decision-making process. <\/li>\n\n\n\n<li>The main objective of this branch of artificial intelligence is to teach machines to collect information from pixels.&nbsp;<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-does-a-computer-read-an-image\"><strong>How does a computer read an image?<\/strong><br><\/h2>\n\n\n\n<p>A digital image is an image composed of picture elements, also known as pixels, each with finite, discrete quantities of numeric representation for its intensity or grey level. So the computer sees an image as numerical values of these pixels and in order to recognise a certain image, it has to recognise the patterns and regularities in this numerical data.<\/p>\n\n\n\n<p>Here is a hypothetical example of how pixels form an image. The darker pixels are represented by a number closer to the zero and lighter pixels are represented by numbers approaching one. All other colours are represented by the numbers between 0 and 1.&nbsp;<\/p>\n\n\n\n<p>But usually, you will find that for any colour image, there are 3 primary channels \u2013 Red, green and blue and the value of each channel varies from 0-255. <br><br>In more simpler terms we can say that a digital image is actually formed by the combination of three basic colour channels&nbsp; Red, green, and blue whereas for a grayscale image we have only one channel whose values also vary from 0-255.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-tutorial-video\"><strong>OpenCV Tutorial Video<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"OpenCV Tutorial for Absolute Beginners | OpenCV Python Tutorial | Great Learning\" width=\"500\" height=\"281\" src=\"https:\/\/www.youtube.com\/embed\/z2b58YVrHt8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-installation\"><strong>OpenCV installation<\/strong><\/h2>\n\n\n\n<p>There are many ways in which you can install OpenCV on your computer. Here are some:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"install-using-anaconda\"><strong>Install using Anaconda<\/strong><\/h3>\n\n\n\n<p>Anaconda is a conditional free and open-source distribution of the Python and R programming languages for scientific computing, that aims to simplify package management and deployment. You can download it from<a href=\"https:\/\/www.anaconda.com\/products\/individual\" target=\"_blank\" rel=\"noreferrer noopener nofollow\"> here<\/a> and install it.<br><\/p>\n\n\n\n<p>After successfully installing anaconda, just go to the anaconda prompt and use this command to install OpenCV:<br><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nconda install -c conda-forge opencv\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>After this command is successfully executed, OpenCV will be available on your computer.Now let us see some other ways to install OpenCV<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"for-windows\"><strong>For Windows<\/strong><\/h3>\n\n\n\n<p>You can use pip to install OpenCV on windows. Pip is a de facto standard package-management system used to install and manage software packages written in Python and it usually comes in installed when you install Python. <br><br>If you do not have Python installed, I would suggest download it from here. Use this command in the command prompt to install OpenCV:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npip install opencv-python\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>After installing it,do check if it is installed successfully.For that just go to the command prompt and type \u2018python\u2019 and hit enter.You should see some message like this:<br><\/p>\n\n\n\n<p>If this is not the message you see, I suggest reinstalling python into your system. Next type import cv2 and if there is no error then it is installed successfully.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"for-mac\"><strong>For Mac<\/strong><\/h3>\n\n\n\n<p>You can use homebrew to install OpenCV as it makes it really easy and you just have to use this command for installing:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nbrew install opencv\n<\/pre><\/div>\n\n\n<p>Now that you have installed the OpenCV onto your system, let's see how it works.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"read-save-images\"><strong>Read &amp; Save Images<\/strong><\/h2>\n\n\n\n<p>Now for OpenCV to work on any image, it must be able to read it. Here we will see how to read a file and save it after we are done with it. Let\u2019s see how to do it:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"imread-function-in-opencv\"><strong>Imread function in OpenCV<\/strong><\/h3>\n\n\n\n<p>We use the imread function to read images. Here is the syntax of this function:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.imread(path, flag)\n<\/pre><\/div>\n\n\n<p>The path parameter takes a string representing the path of the image to be read.The file should be in the working directory or we must give the full path to the image.<\/p>\n\n\n\n<p>The other parameter is the flag which is used to specify how our image should be read. Here are possible values that it takes and their working:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv2.IMREAD_COLOR: It specifies to convert the image to the 3 channel BGR \ncolour image. Any transparency of image will be neglected. It is the default\nflag. Alternatively, we can passinteger value 1 for this flag.\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv2.IMREAD_GRAYSCALE: It specifies to convert an image to thesingle channel \ngrayscale image. Alternatively, we can pass integer value 0 for this flag.\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv2.IMREAD_UNCHANGED: It specifies to load an image as such including alpha \nchannel.Alternatively, we can pass integer value -1 for this flag.\n<\/pre><\/div>\n\n\n<p>Usually the method imread() returns an image that is loaded from the specified file but in case the image cannot be read because of unsupported file format, missing file, unsupported or invalid format, it just returns a matrix. Here is a example in which we read an image from my storage.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#importing the opencv module  \nimport cv2  \n# using imread(&#039;path&#039;) and 1 denotes read as  color image  \nimg = cv2.imread(&#039;dog.jpg&#039;,1)  \n#This is using for display the image  \ncv2.imshow(&#039;image&#039;,img)  \ncv2.waitKey() # This is necessary to be required so that the image doesn&#039;t close immediately.  \n#It will run continuously until the key press.  \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"imwrite-function-in-opencv\"><strong>Imwrite function in OpenCV<\/strong><\/h3>\n\n\n\n<p>We can use OpenCV\u2019s imwrite() function to save an image in a storage device and the file extension defines the image format as shown in the example below. The syntax is the following:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv2.imwrite(filename, image)\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>Parameters: <\/p>\n\n\n\n<p>filename: A string representing the file name. The filename must include image format. <\/p>\n\n\n\n<p>image: It is the image that is to be saved.<\/p>\n\n\n\n<p> Here is an example in which we use this function: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2  \n# read image  \nimg = cv2.imread(r&#039;C:UsersMirzadog.jpeg&#039;, 1)  \n# save image  \nstatus = cv2.imwrite(r&#039;C:UsersMirzadog.jpeg&#039;,img)  \nprint(&quot;Image written sucess? : &quot;, status)  \n<\/pre><\/div>\n\n\n<p>If the file is successfully written then this function returns True and thus it is important to store the outcome of this function.In the example above,we have done the same and used the \u2018status\u2019 variable to know if the file is written successfully.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"basic-operation-on-images\"><strong>Basic Operation On images<\/strong><\/h2>\n\n\n\n<p>In this section,we are going to discuss some of the basic operations that we can do on the images once we have successfully read them.The operations we are going to do here ae:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Access pixel values and modify them<\/li>\n\n\n\n<li>Access image properties<\/li>\n\n\n\n<li>Set a Region of Interest (ROI)<\/li>\n\n\n\n<li>Split and merge image channels<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"access-pixel-values-and-modify-them\"><strong>Access pixel values and modify them<\/strong><\/h3>\n\n\n\n<p>So there are basically two ways to access a pixel value in an Image and modify them. First let us see how we can access a particular pixel value of an image.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport cv2 as cv\nimg = cv.imread(r&#039;C:UsersMirzadog.jpeg&#039;)\npx = img&#x5B;100,100]\nprint( px )\n<\/pre><\/div>\n\n\n<p>Output: <\/p>\n\n\n\n<p>[157&nbsp;166&nbsp;200] <\/p>\n\n\n\n<p>Now as you can see we got a list containing 3 values.As we know OpenCV stores the color image as BGR color image,so the first value in the list is the value of the blue channel of this particular pixel, and the rest are values for green and red channels.<\/p>\n\n\n\n<p>We can also access only one of the channels as shown below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# accessing only blue pixel\nblue = img&#x5B;100,100,0]\nprint( blue )\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n\n<p>157 <\/p>\n\n\n\n<p>To modify the values, we just need to access the pixel and then overwrite it with a value as shown below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimg&#x5B;100,100] = &#x5B;255,255,255]\nprint( img&#x5B;100,100] )\n<\/pre><\/div>\n\n\n<p>Output: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;255\u00a0255\u00a0255] \n<\/pre><\/div>\n\n\n<p>This method to access and modify the pixel values is slow so you should make use of NumPy library as it is&nbsp; optimized for fast array calculations. For accessing individual pixel values, the Numpy array methods, array.item() and array.itemset() are considered better as&nbsp; they always return a scalar. <br><br>However, if you want to access all the B,G,R values, you will need to call array.item() separately for each value as shown below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# accessing RED value\nimg.item(10,10,2)\n&gt;&gt;59\n# modifying RED value\nimg.itemset((10,10,2),100)\nimg.item(10,10,2)\n&gt;&gt;100\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"access-image-properties\"><strong>Access Image properties<\/strong><br><\/h3>\n\n\n\n<p>What do we mean by image properties here? Often it is important to know the size(total number of pixels in the image), number of rows, columns, and channels.We can access the later three by using the shape() method as shown below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nprint( img.shape )\n&gt;&gt;(342, 548, 3)\nprint( img.size )\n&gt;&gt;562248\n<\/pre><\/div>\n\n\n<p>So here we have three numbers in the returned tuple, these are number of rows, number of columns and number of channels respectively. Incase an image is grayscale, the tuple returned contains only the number of rows and columns.<\/p>\n\n\n\n<p>Often a large number of errors in OpenCV-Python code are caused by invalid datatype so img.dtype which returns the image datatype is very important while debugging. <\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nprint( img.dtype )\n&gt;&gt;uint8\n<\/pre><\/div>\n\n\n<p><strong>Image ROI(Region of interest)<\/strong><\/p>\n\n\n\n<p>Often you may come across some images where you are only interested in a specific region. Say you want to detect eyes in an image, will you search the entire image, possibly not as that may not fetch accurate results. But we know that eyes are a part of face, so it is better to detect a face first ,thus here the face is our ROI. You may want to have a look at the article <a href=\"https:\/\/www.mygreatlearning.com\/blog\/viola-jones-algorithm\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Face detection using<\/strong> <strong>Viola-Jones algorithm<\/strong><\/a>&nbsp;where we detect the faces and then find eyes in the area we found faces.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"splitting-and-merging-image-channels\"><strong>Splitting and Merging Image Channels<\/strong><\/h3>\n\n\n\n<p>We can also split the channels from an image and then work on each channel separately. Or sometimes you may need to merge them back together, here is how we do it:<\/p>\n\n\n\n<p>But this method is painfully slow, so we can also use the <a href=\"https:\/\/www.mygreatlearning.com\/blog\/python-numpy-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">Numpy<\/a> to do the same, here is how:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nb,g,r = cv.split(img)\nimg = cv.merge((b,g,r))\nb = img&#x5B;:,:,0]\ng = img&#x5B;:,:,1]\nr = img&#x5B;:,:,2]\n<\/pre><\/div>\n\n\n<p>Now suppose you want to just set all the values in the red channel to zero, here is how to do that:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#sets all values in red channel as zero\nimg&#x5B;:,:,2] = 0\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-resize-image\"><strong>OpenCV Resize Image<\/strong><\/h2>\n\n\n\n<p>Usually when working on images, we often need to resize the images according to certain requirements. <br><br>Mostly you will do such operation in Machine learning and deep learning as it reduces the time of training of a neural network. As the number of pixels in an image increases, the more is the number of input nodes that in turn increases the complexity of the model. We use an inbuilt resize() method to resize an image.<\/p>\n\n\n\n<p>Syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv2.resize(s, size,fx,fy,interpolation)\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p><strong>Parameters:<\/strong><\/p>\n\n\n\n<p>s - input image (required). <\/p>\n\n\n\n<p>size - desired size for the output image after resizing (required) <\/p>\n\n\n\n<p>fx - Scale factor along the horizontal axis.(optional) <\/p>\n\n\n\n<p>fy - Scale factor along the vertical axis. <\/p>\n\n\n\n<p>Interpolation(optional) - This flag uses following methods:<\/p>\n\n\n\n<p>Interpolation(optional) - This flag uses following methods:<br>INTER_NEAREST \u2013 a nearest-neighbor interpolation<br>INTER_LINEAR \u2013 a bilinear interpolation (used by default)&nbsp;<br>INTER_AREA \u2013 resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire\u2019-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.<br>INTER_CUBIC \u2013 a bicubic interpolation over 4\u00d74 pixel neighborhood&nbsp;<br>INTER_LANCZOS4 \u2013 a Lanczos interpolation over 8\u00d78 pixel neighborhood<\/p>\n\n\n\n<p> Here is an example of how we can use this method: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimport numpy as np\n\n#importing the opencv module  \nimport cv2  \n# using imread(&#039;path&#039;) and 1 denotes read as  color image  \nimg = cv2.imread(&#039;dog.jpg&#039;,1)  \nprint(img.shape)\nimg_resized=cv2.resize(img, (780, 540),  \n               interpolation = cv2.INTER_NEAREST) \ncv2.imshow(&quot;Resized&quot;,img_resized)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex\"><figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/dog.jpg\"><img decoding=\"async\" width=\"275\" height=\"183\" data-id=\"23024\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/dog.jpg\" alt=\"\" class=\"wp-image-23024\"><figcaption class=\"wp-element-caption\">original<\/figcaption><\/figure>\n\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1.png\"><img decoding=\"async\" width=\"977\" height=\"717\" data-id=\"23026\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1.png\" alt=\"\" class=\"wp-image-23026\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1.png 977w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1-300x220.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1-768x564.png 768w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1-696x511.png 696w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1-572x420.png 572w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/q1-80x60.png 80w\" sizes=\"(max-width: 977px) 100vw, 977px\" \/><figcaption class=\"wp-element-caption\">resized<\/figcaption><\/figure>\n<\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-image-rotation\"><strong>OpenCV Image Rotation<\/strong><\/h2>\n\n\n\n<p>We may need to rotate an image in some of the cases and we can do it easily by using OpenCV .We use cv2.rotate() method to rotate a 2D array in multiples of 90 degrees. Here is the syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.rotate( src, rotateCode&#x5B;, dst] )\n<\/pre><\/div>\n\n\n<p>Parameters:<br>src: It is the image to be rotated.<br>rotateCode: It is an enum to specify how to rotate the array.Here are some of the possible values :<br>cv2.cv2.ROTATE_90_CLOCKWISE<br>cv2.ROTATE_180<br>cv2.ROTATE_90_COUNTERCLOCKWISE<\/p>\n\n\n\n<p>Here is an example using this function.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimport numpy as np\n\n#importing the opencv module  \nimport cv2  \n# using imread(&#039;path&#039;) and 1 denotes read as  color image  \nimg = cv2.imread(&#039;dog.jpg&#039;,1)  \nprint(img.shape)\nimage = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) \ncv2.imshow(&quot;Rotated&quot;,image)\ncv2.waitKey()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n<figure class=\"wp-block-image aligncenter zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/rota.png\"><img decoding=\"async\" width=\"235\" height=\"387\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/rota.png\" alt=\"\" class=\"wp-image-23031\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/rota.png 235w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/rota-182x300.png 182w\" sizes=\"(max-width: 235px) 100vw, 235px\" \/><figcaption class=\"wp-element-caption\">rotated image<\/figcaption><\/figure>\n\n\n\n<p>Now what if we want to rotate the image by a certain angle.We can use another method for that.First calculate the affine matrix that does the affine transformation (linear mapping of pixels) by using the getRotationMatrix2D method,next we warp the input image with the affine matrix using warpAffine method.<\/p>\n\n\n\n<p>Here is the syntax of these functions:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv2.getRotationMatrix2D(center, angle, scale)\ncv2.warpAffine(Img, M, (W, H))\n<\/pre><\/div>\n\n\n<p>center: center of the image (the point about which rotation has to happen)<br>angle: angle by which image has to be rotated in the anti-clockwise direction.<br>scale: scales the image by the value provided,1.0 means the shape is preserved.<br>H:height of image<br>W: width of the image.<br>M: affine matrix returned by cv2.getRotationMatrix2D<br>Img: image to be rotated.<\/p>\n\n\n\n<p>Here is an example in which we rotate an image by various angles. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimport numpy as np\n\n#importing the opencv module  \nimport cv2  \n# using imread(&#039;path&#039;) and 1 denotes read as  color image  \nimg = cv2.imread(&#039;dog.jpg&#039;,1)  \n# get image height, width\n(h, w) = img.shape&#x5B;:2]\n# calculate the center of the image\ncenter = (w \/ 2, h \/ 2)\n \nscale = 1.0\n \n# Perform the counter clockwise rotation holding at the center\n# 45 degrees\nM = cv2.getRotationMatrix2D(center, 45, scale)\nprint(M)\nrotated45 = cv2.warpAffine(img, M, (h, w))\n \n# 110 degrees\nM = cv2.getRotationMatrix2D(center,110, scale)\nrotated110 = cv2.warpAffine(img, M, (w, h))\n \n# 150 degrees\nM = cv2.getRotationMatrix2D(center, 150, scale)\nrotated150 = cv2.warpAffine(img, M, (h, w))\n \n \ncv2.imshow(&#039;Original Image&#039;,img)\ncv2.waitKey(0) # waits until a key is pressed\ncv2.destroyAllWindows() # destroys the window showing image\n \ncv2.imshow(&#039;Image rotated by 45 degrees&#039;,rotated45)\ncv2.waitKey(0) # waits until a key is pressed\ncv2.destroyAllWindows() # destroys the window showing image\n \ncv2.imshow(&#039;Image rotated by 110 degrees&#039;,rotated110)\ncv2.waitKey(0) # waits until a key is pressed\ncv2.destroyAllWindows() # destroys the window showing image\n \ncv2.imshow(&#039;Image rotated by 150 degrees&#039;,rotated150)\ncv2.waitKey(0) # waits until a key is pressed\ncv2.destroyAllWindows() # destroys the window showing image\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n\n<figure class=\"wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-2 is-layout-flex wp-block-gallery-is-layout-flex\"><figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/45.png\"><img decoding=\"async\" width=\"232\" height=\"385\" data-id=\"23039\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/45.png\" alt=\"\" class=\"wp-image-23039\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/45.png 232w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/45-181x300.png 181w\" sizes=\"(max-width: 232px) 100vw, 232px\" \/><\/figure>\n\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/110.png\"><img decoding=\"async\" width=\"349\" height=\"270\" data-id=\"23040\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/110.png\" alt=\"\" class=\"wp-image-23040\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/110.png 349w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/110-300x232.png 300w\" sizes=\"(max-width: 349px) 100vw, 349px\" \/><\/figure>\n\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/150.png\"><img decoding=\"async\" width=\"230\" height=\"381\" data-id=\"23041\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/150.png\" alt=\"\" class=\"wp-image-23041\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/150.png 230w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/150-181x300.png 181w\" sizes=\"(max-width: 230px) 100vw, 230px\" \/><\/figure>\n<figcaption class=\"blocks-gallery-caption wp-element-caption\">rotated images<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-drawing-functions\"><strong>OpenCV Drawing Functions<\/strong><br><\/h2>\n\n\n\n<p>We may require to draw certain shapes on an image such as circle, rectangle, ellipse, polylines, convex, etc. and we can easily do this using OpenCV. It is often used when we want to highlight any object in the input image for example in case of face detection, we might want to highlight the face with a rectangle. <br><br>Here we will learn about the drawing functions such as circle, rectangle, lines, polylines and also see how to write text on an image.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"drawing-circle\"><strong>Drawing circle:<\/strong><\/h3>\n\n\n\n<p>We use the method to circle to draw a circle in an image. Here is the syntax and parameters:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.circle(image, center_coordinates, radius, color, thickness)\n<\/pre><\/div>\n\n\n<p>Parameters:&nbsp;<br>image: It is the input image on which a circle is to be drawn.&nbsp;<br>center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).&nbsp;<br>radius: It is the radius of the circle.&nbsp;<br>color: It is the color of the border line of the circle to be drawn. We can pass a tuple For in BGR,&nbsp; eg: (255, 0, 0) for blue color.&nbsp;<br>thickness: It is the thickness of the circle border line in px. Thickness of -1 px will fill the circle shape by the specified color.<br>Return Value: It returns an image.<\/p>\n\n\n\n<p>Here are the few of the examples:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np  \nimport cv2  \nimg = cv2.imread(r&#039;C:UsersMirzadog.jpeg&#039;, 1)  \ncv2.circle(img,(80,80), 55, (255,0,0), -1)  \ncv2.imshow(&#039;image&#039;,img)  \ncv2.waitKey(0)  \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n\n<p><strong>Drawing Rectangle<\/strong><\/p>\n\n\n\n<p>In a similar we can draw a rectangle. Here is the the syntax for this function:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.rectangle(image, start_point, end_point, color, thickness)\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>image: It is the input image on which rectangle is to be drawn.<br>start_point: It is the starting coordinates(top left vertex) of the rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).<br>end_point: It is the ending coordinates(bottom right) of the rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).<br>color: It is the color of the border line of the rectangle to be drawn. We can pass a tuple For in BGR,&nbsp; eg: (255, 0, 0) for blue color.&nbsp;<br>thickness: It is the thickness of the rectangle border line in px. Thickness of -1 px will fill the rectangle shape by the specified color.<\/p>\n\n\n\n<p>Return Value: It returns an image.<\/p>\n\n\n\n<p>Here is an example of this function:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np  \nimport cv2  \nimg = cv2.imread(r&#039;C:UsersMirzadog.jpeg&#039;, 1)  \ncv2.rectangle(img,(15,25),(200,150),(0,255,255),15)  \ncv2.imshow(&#039;image&#039;,img)  \ncv2.waitKey(0)  \ncv2.destroyAllWindows()  \n<\/pre><\/div>\n\n\n<p><strong>Drawing Lines<\/strong><\/p>\n\n\n\n<p>Here is the syntax of the line method using which we can make lines on an image.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.line(image, start_point, end_point, color, thickness)\n<\/pre><\/div>\n\n\n<p>Parameters:<br>image: It is the input image on which line is to be drawn.<br>start_point: It is the starting coordinates of the line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).<br>end_point: It is the ending coordinates of the line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).<br>color: It is the color of the line to be drawn. We can pass a tuple For in BGR,&nbsp; eg: (255, 0, 0) for blue color.&nbsp;<br>thickness: It is the thickness of the line in px.<\/p>\n\n\n\n<p>Return Value: It returns an image.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np  \nimport cv2  \nimg = cv2.imread(r&#039;C:UsersMirzadog.jpeg&#039;, 1)  \n#defining points for polylines  \npts = np.array(&#x5B;&#x5B;100,50],&#x5B;200,300],&#x5B;700,200],&#x5B;500,100]], np.int32)  \n# pts = pts.reshape((-1,1,2))  \ncv2.polylines(img, &#x5B;pts], True, (0,255,255), 3)  \ncv2.imshow(&#039;image&#039;,img)  \ncv2.waitKey(0)  \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n\n<p><strong>Drawing Polylines<\/strong><\/p>\n\n\n\n<p>We can draw the polylines using the polylines() method on the image. And these can be used to draw polygonal curves on the image. The syntax is given below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.polyLine(image, arr, is_closed, color, thickness)\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>img - It represents an image.<br>arr -represents the coordinates of vertices into an array of shape nx1x2 where n is number of vertices and it should be of type int32.<br>is_Closed - It is a flag that indicates whether the drawn polylines are closed or not.<br>color - Color of polylines. We can pass a tuple For in BGR,&nbsp; eg: (255, 0, 0) for blue color.&nbsp;<br>thickness - It represents the Thickness of the polyline's edges.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np  \nimport cv2  \nimg = cv2.imread(r&#039;C:UsersMirzadog.jpeg&#039;, 1)  \n#defining points for polylines  \npts = np.array(&#x5B;&#x5B;100,50],&#x5B;200,300],&#x5B;700,200],&#x5B;500,100]], np.int32)  \n# pts = pts.reshape((-1,1,2))  \ncv2.polylines(img, &#x5B;pts], True, (0,255,255), 3)  \ncv2.imshow(&#039;image&#039;,img)  \ncv2.waitKey(0)  \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n\n<p><strong>Write text on an image<\/strong><\/p>\n\n\n\n<p>We can write text on the image by using the putText() method. The syntax is given below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.putText(img, text, org, font,fontScale color)\n<\/pre><\/div>\n\n\n<p>Parameters:<br>img: It represents the input image on which we have to write text<br>text: The text which we want to write on the image.<br>org: It denotes the Bottom-left corner of the text string on the image. So it is used to set the location of text on the image<br>font: the font of text. Here is the list of supported fonts.<br>fontScale: The scale of the font by which you can increase or decrease size<br>color: Represents the color. We can pass a tuple For in BGR,&nbsp; eg: (255, 0, 0) for blue color.&nbsp;<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np  \nimport cv2  \nfont = cv2.FONT_HERSHEY_SIMPLEX  \nmg = cv2.imread(r&#039;C:UsersMirzadog.jpeg&#039;, 1)  \ncv2.putText(img,&#039;Dog&#039;,(10,500), font, 1,(255,255,255),2)  \n#Display the image  \ncv2.imshow(&quot;image&quot;,img)  \ncv2.waitKey(0) \n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-blob-detection\"><strong>OpenCV Blob Detection<\/strong><\/h2>\n\n\n\n<p>Blob stands for Binary Large Object where the term \"Large\" focuses on the object of a specific size, and that other \"small\" binary objects are usually considered as noise.<\/p>\n\n\n\n<p>In simpler terms, a Blob is a group of connected pixels which we can find in an image and all of these pixels have some common property. In the image below, the coloured connected regions are blobs, and the goal of blob detection is to identify and mark these regions( marked by red circle).<\/p>\n\n\n\n<p>Using OpenCV\u2019s SimpleBlobDetector method, we can&nbsp; easily find blobs in our images.But how does this method work?Let us see this in detail:<br><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Thresholding<\/strong> :First the algorithm converts the source images to several binary images by applying thresholding with various thresholds.We define two threshold values,viz- minThreshold (inclusive) to maxThreshold (exclusive)&nbsp; and start from threshold value equal to minThreshold.Then it is incremented by thresholdStep until we reach maxThreshold,so the first threshold is minThreshold, the second is minThreshold + thresholdStep and so on.<\/li>\n\n\n\n<li><strong>Grouping <\/strong>: In each binary image, we have a curve joining all the continuous points (along the boundary), having the same color or intensity.<\/li>\n\n\n\n<li><strong>Merging<\/strong>&nbsp; : The centers of the binary blobs in the binary images are computed, and&nbsp; blobs located closer than minDistBetweenBlobs(minimum distance between two blobs) are merged.<\/li>\n\n\n\n<li><strong>Center &amp; Radius Calculation<\/strong> :&nbsp; The centers and radii of the new merged blobs are computed and returned.<\/li>\n<\/ol>\n\n\n\n<p>This class can perform several filtrations of returned blobs by setting filterBy* to True to turn on corresponding filtration. Available filtrations are as following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>By color<\/strong>. We define a parameter blobColor to filter the blobs of colours we are interested in. Set blobColor equal to zero to extract dark blobs and to extract light blobs,set it to 255. This filter compares the intensity of a binary image at the center of a blob to blobColor and filters accordingly.<\/li>\n\n\n\n<li><strong>By area<\/strong>. By using this filter the extracted blobs have an area between minArea (inclusive) and maxArea (exclusive).<\/li>\n\n\n\n<li><strong>By circularity<\/strong>. By using this filter the extracted blobs have circularity between minCircularity (inclusive) and maxCircularity (exclusive).<\/li>\n\n\n\n<li><strong>By ratio of the minimum inertia to maximum inertia<\/strong>.By using this filter the extracted blobs have this ratio between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive).<\/li>\n\n\n\n<li><strong>By convexity<\/strong>.By using this filter the extracted blobs have convexity (area \/ area of blob convex hull) between minConvexity (inclusive) and maxConvexity (exclusive).<\/li>\n<\/ul>\n\n\n\n<p>By default, the values of&nbsp; these parameters are tuned to extract dark circular blobs.<\/p>\n\n\n\n<p>Here is an example of how to use simple SimpleBlobDetector()<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2  \nimport numpy as np;  \n  \nimg = cv2.imread(r&quot;pic1.jpeg&quot;, cv2.IMREAD_GRAYSCALE)  \n# Set up the detector with default parameters.  \ndetector = cv2.SimpleBlobDetector()  \n  \n# Detecting blobs.  \nkeypoints = detector.detect(img)  \n# Draw detected blobs as red circles.  \n# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob  \nim_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array(&#x5B;]), (0, 0, 255),  \n                                      cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)  \n# Show keypoints  \ncv2.imshow(&quot;Keypoints&quot;, im_with_keypoints)  \ncv2.waitKey(0)  \n<\/pre><\/div>\n\n\n<p>Now here is an example in which we use the filters mentioned above:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimport numpy as np;\n\n# Read image\nim = cv2.imread(&quot;blob.jpg&quot;)\n\n# Setup SimpleBlobDetector parameters.\nparams = cv2.SimpleBlobDetector_Params()\n\n# Change thresholds\nparams.minThreshold = 10\nparams.maxThreshold = 200\n\n\n# Filter by Area.\nparams.filterByArea = True\nparams.minArea = 1500\n\n# Filter by Circularity\nparams.filterByCircularity = True\nparams.minCircularity = 0.1\n\n# Filter by Convexity\nparams.filterByConvexity = True\nparams.minConvexity = 0.87\n\n# Filter by Inertia\nparams.filterByInertia = True\nparams.minInertiaRatio = 0.01\n\n# Create a detector with the parameters\ndetector = cv2.SimpleBlobDetector(params)\n\n\n# Detect blobs.\nkeypoints = detector.detect(im)\n\n# Draw detected blobs as red circles.\n# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures\n# the size of the circle corresponds to the size of blob\n\nim_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array(&#x5B;]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n# Show blobs\ncv2.imshow(&quot;Keypoints&quot;, im_with_keypoints)\ncv2.waitKey(0)\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"canny-edge-detection\"><strong>Canny Edge Detection<\/strong><\/h2>\n\n\n\n<p>Edge detection is an image processing technique used for finding the boundaries of objects within images. Here we will use a popular edge detection algorithm Canny Edge Detection, developed by John F. Canny. In OpenCV, we have Canny() method to implement this algorithm. Here is the syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nedges = cv2.Canny(img, minVal, maxVal, apertureSize, L2gradient)\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>Parameters -<\/p>\n\n\n\n<p>img: input image whose edges we want to detect.<br>minVal: Minimum intensity gradient (required)<br>maxVal: Maximum intensity gradient (required)<br>L2gradient: is a flag with default value =False, indicating the default L1 norm is enough to calculate the image gradient magnitude, if its is set as True a more accurate L2 norm is used to calculate the image gradient magnitude but it is computationally more expensive.<br>aperture: aperture size for the Sobel operator.<\/p>\n\n\n\n<p>As we can see we have two threshold values, minVal and maxVal. Any edges with intensity gradient more than maxVal are sure to be edges.also those edges with intensity gradient less than minVal are sure to be non-edges and are discarded. <br><br>The edges which lie between these two thresholds are classified edges or non-edges based on their connectivity with the \u2018sure edges\u2019. If they are connected to \"sure-edge\" pixels, they are considered to be part of edges. Otherwise, they are also discarded as non-edges.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimg = cv2.imread(&#039;dog.jpg&#039;)\nedges = cv2.Canny(img,200,300,True)\ncv2.imshow(&quot;Edge Detected Image&quot;, edges)  \ncv2.imshow(&quot;Original Image&quot;, img)  \ncv2.waitKey(0)  # waits until a key is pressed  \ncv2.destroyAllWindows()  # destroys the window showing image\n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/edge.png\"><img decoding=\"async\" width=\"696\" height=\"272\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/edge.png\" alt=\"\" class=\"wp-image-23251\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/edge.png 696w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/edge-300x117.png 300w\" sizes=\"(max-width: 696px) 100vw, 696px\" \/><\/figure>\n\n\n\n<p>Now we can also do this in real-time, here is how:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# import libraries of python OpenCV    \nimport cv2  \n  \n# import Numpy by alias name np  \nimport numpy as np  \n  \n# capture frames from a camera   \ncap = cv2.VideoCapture(0)  \n  \n# loop runs if capturing has been initialized   \nwhile (1):  \n  \n    # reads frames from a camera   \n    ret, frame = cap.read()  \n  \n    # Display an original image   \n    cv2.imshow(&#039;Original&#039;, frame)  \n  \n    # discovers edges in the input image image and   \n    # marks them in the output map edges   \n    edges = cv2.Canny(frame, 100, 200,True)  \n  \n    # Display edges in a frame   \n    cv2.imshow(&#039;Edges&#039;, edges)  \n  \n    if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n        break\n  \n# Close the window   \ncap.release()  \n  \n# De-allocate any associated memory usage   \ncv2.destroyAllWindows()  \n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-image-smoothing\"><strong>OpenCV Image Smoothing<\/strong><\/h2>\n\n\n\n<p>Image smoothing is an image processing technique used for removing the noise in an image.Blurring(smoothing) removes low-intensity edges and is also beneficial in hiding the details; for example, blurring is required in many cases, such as hiding any confidential information in an image.OpenCV provides mainly the following type of blurring techniques.<\/p>\n\n\n\n<p>Here are a few of the methods that we are going to use for smoothing an image:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>OpenCV averaging<\/li>\n\n\n\n<li>OpenCV median Blur<\/li>\n\n\n\n<li>OpenCV Gaussian Blur<\/li>\n\n\n\n<li>OpenCV Bilateral Filter<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"opencv-averaging\"><strong>OpenCV averaging<\/strong><\/h3>\n\n\n\n<p>In this technique, we normalize the image with a box filter. It calculates the average of all the pixels which are under the kernel area(box filter) and replaces the value of the pixel at the center of the box filter with the calculated average. OpenCV provides the cv2.blur() to perform this operation. The syntax of cv2.blur() function is as follows.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.blur(src, ksize,anchor, borderType)\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>src: It is the image which is to be blurred.<br>ksize: A tuple representing the blurring kernel size.<br>anchor: It is a variable of type integer representing anchor point and it\u2019s default value Point is (-1, -1) which means that the anchor is at the kernel center.<br>borderType: It represents the type of border to be used for the output.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimg = cv2.imread(&#039;dog.jpg&#039;)\ncv2.imshow(&#039;Original Image&#039;,img)  \ncv2.imshow(&#039;cv2.blur output&#039;, cv2.blur(img, (3,3)))  \ncv2.waitKey(0)  \ncv2.destroyAllWindows()  \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/cv2.blur_.png\"><img decoding=\"async\" width=\"692\" height=\"272\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/cv2.blur_.png\" alt=\"\" class=\"wp-image-23252\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/cv2.blur_.png 692w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/cv2.blur_-300x118.png 300w\" sizes=\"(max-width: 692px) 100vw, 692px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"opencv-median-blur\"><strong>OpenCV median Blur<\/strong>&nbsp;<\/h3>\n\n\n\n<p>In this technique, the median of all the pixels under the kernel window is computed and the central pixel is replaced with this median value. It has one advantage over the Gaussian and box filters, that being the filtered value for the central element is always replaced by some pixel value in the image which is not the case in case of either Gaussian or box filters. OpenCV provides a function medianBlur() that can be used to easily implement this kind of smoothing. Here is the syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.medianBlur(src, dst, ksize)\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>src- It represents the source (input image).<br>dst - It represents the destination (output image).<br>ksize - It represents the size of the kernel.<\/p>\n\n\n\n<p>Consider the following example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimg = cv2.imread(&#039;dog.jpg&#039;)\ncv2.imshow(&#039;Original Image&#039;,img)  \ncv2.imshow(&#039;cv2.medianBlur output&#039;, cv2.medianBlur(img,5))  \ncv2.waitKey(0)  \ncv2.destroyAllWindows()  \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/medianblur.png\"><img decoding=\"async\" width=\"688\" height=\"269\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/medianblur.png\" alt=\"\" class=\"wp-image-23253\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/medianblur.png 688w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/medianblur-300x117.png 300w\" sizes=\"(max-width: 688px) 100vw, 688px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"opencv-gaussian-blur\"><strong>OpenCV Gaussian Blur<\/strong><\/h3>\n\n\n\n<p>In this technique, a Gaussian function(kernel) instead of a box filter to blur the image. The width and height of the kernel needs to be specified and they should be positive and odd. We also have to specify the standard deviation in the directions X and Y and are represented by sigmaX and sigmaY respectively. If both sigmaX and sigmaY are given as zeros, they are calculated from the kernel size and if we only specify sigmaX, sigmaY is set to the same value. Gaussian blurring is highly effective when removing Gaussian noise from an image. In OpenCV we have a function GaussianBlur() to implement this technique easily. Here is the&nbsp;syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nGaussianBlur(src, dst, ksize, sigmaX,sigmaY)\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>src \u2212 Input image which is to be blurred<br>dst \u2212 output image of the same size and type as src.<br>ksize \u2212 A Size object representing the size of the kernel.<br>sigmaX \u2212 A variable of the type double representing the Gaussian kernel standard deviation in X direction.<br>sigmaY \u2212 A variable of the type double representing the Gaussian kernel standard deviation in Y direction.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimg = cv2.imread(&#039;dog.jpg&#039;)\ncv2.imshow(&#039;Original Image&#039;,img)  \ncv2.imshow(&#039;cv2.GaussianBlur output&#039;, cv2.GaussianBlur(img, (5, 5), cv2.BORDER_DEFAULT))     \ncv2.waitKey(0)  \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/gaussiaf.png\"><img decoding=\"async\" width=\"684\" height=\"266\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/gaussiaf.png\" alt=\"\" class=\"wp-image-23254\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/gaussiaf.png 684w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/gaussiaf-300x117.png 300w\" sizes=\"(max-width: 684px) 100vw, 684px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"opencv-bilateral-filter\"><strong>OpenCV Bilateral Filter<\/strong><\/h3>\n\n\n\n<p>This method of noise removal is highly effective but is slower compared to other filters. The Gaussian filter blurred the edges too and that is not what we want, but this filter makes sure that only those pixels with similar intensities to the central pixel are considered for blurring, thus preserving the edges since pixels at edges will have large intensity variation. In OpenCV we have cv.bilateralFilter() method that can implement this filter. Here is the&nbsp;syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.bilateralFilter(src, dst, d, sigmaColor,sigmaSpace, borderType)\u00a0\u00a0\n<\/pre><\/div>\n\n\n<p>Parameters:<br>src Source 8-bit or floating-point, 1-channel or 3-channel image.<br>dst Destination image of the same size and type as src .<br>d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, it is computed from sigmaSpace.<br>sigmaColor Filter sigma in the color space. A larger value of the parameter means that farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting in larger areas of semi-equal color.<br>sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that farther pixels will influence each other as long as their colors are close enough (see sigmaColor ). When d&gt;0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is proportional to sigmaSpace.<br>borderType border mode used to extrapolate pixels outside of the image, see the BorderTypes available here.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimg = cv2.imread(&#039;dog.jpg&#039;)\ncv2.imshow(&#039;Original Image&#039;,img)  \ncv2.imshow(&#039;bilateral Image&#039;, cv2.bilateralFilter(img,9,75,75))  \ncv2.waitKey(0)  \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/bilateral.png\"><img decoding=\"async\" width=\"688\" height=\"265\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/bilateral.png\" alt=\"\" class=\"wp-image-23255\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/bilateral.png 688w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/bilateral-300x116.png 300w\" sizes=\"(max-width: 688px) 100vw, 688px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-image-threshold\"><strong>OpenCV Image Threshold<\/strong><\/h2>\n\n\n\n<p>Thresholding is a popular segmentation technique, used for separating an object considered as a foreground from its background.In this technique we assign pixel values in relation to the threshold value provided.This technique of thresholding is done on grayscale images,so initially, the image has to be converted in grayscale color space.Here we will discuss two different approaches taken when performing thresholding on an image:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Simple Thresholding<\/li>\n\n\n\n<li>Adaptive Thresholding<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"simple-thresholding\"><strong>Simple Thresholding:<\/strong><\/h3>\n\n\n\n<p>In this basic Thresholding technique, for every pixel, the same threshold value is applied. If the pixel value is smaller than the threshold, it is set to a certain value(usually zero) , otherwise, it is set to another value(usually maximum value) .There are various variations of this technique as shown below.<br><\/p>\n\n\n\n<p>In OpenCV, we use cv2.threshold function to implement it. Here is the syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>-&gt; source: Input Image array (must be in Grayscale).<br>-&gt; thresholdValue: Value of Threshold below and above which pixel values will change accordingly.<br>-&gt; maxVal: Maximum value that can be assigned to a pixel.<br>-&gt; thresholdingTechnique: The type of thresholding to be applied.Here are various types of thresholding we can use<\/p>\n\n\n\n<p>cv2.THRESH_BINARY: If&nbsp; the pixel intensity is greater than the threshold, the pixel value is set to 255(white), else it is set to 0 (black).<br>cv2.THRESH_BINARY_INV: Inverted or Opposite case of cv2.THRESH_BINARY.If&nbsp; the pixel intensity is greater than the threshold, the pixel value is set to 0(black), else it is set to 255 (white).<br>cv.THRESH_TRUNC: If&nbsp; the pixel intensity is greater than the threshold,the pixel values are set to be the same as the threshold. All other values remain the same.<br>cv.THRESH_TOZERO: Pixel intensity is set to 0, for all the pixels intensity, less than the threshold value.All other pixel values remain same<br>cv.THRESH_TOZERO_INV: Inverted or Opposite case of cv2.THRESH_TOZERO.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2  \nimport numpy as np  \n  \n# path to input image is specified and   \n# image is loaded with imread command  \nimage = cv2.imread(&#039;gl.png&#039;)  \n  \n\n# to convert the image in grayscale  \nimg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \n  \nthreshold=160\nret, thresh1 = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) \nret, thresh2 = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY_INV) \nret, thresh3 = cv2.threshold(img, threshold, 255, cv2.THRESH_TRUNC) \nret, thresh4 = cv2.threshold(img, threshold, 255, cv2.THRESH_TOZERO) \nret, thresh5 = cv2.threshold(img, threshold, 255, cv2.THRESH_TOZERO_INV) \n  \n# the window showing output images \n# with the corresponding thresholding  \n# techniques applied to the input images \ncv2.imshow(&#039;Original&#039;,image)\ncv2.imshow(&#039;Binary Threshold&#039;, thresh1) \ncv2.imshow(&#039;Binary Threshold Inverted&#039;, thresh2) \ncv2.imshow(&#039;Truncated Threshold&#039;, thresh3) \ncv2.imshow(&#039;Zero Threshold&#039;, thresh4) \ncv2.imshow(&#039;Zero Inverted&#039;, thresh5) \n    \n# De-allocate any associated memory usage   \ncv2.waitKey(0)\ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/thres.png\"><img decoding=\"async\" width=\"838\" height=\"267\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/thres.png\" alt=\"\" class=\"wp-image-23256\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/thres.png 838w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/thres-300x96.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/thres-768x245.png 768w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/thres-696x222.png 696w\" sizes=\"(max-width: 838px) 100vw, 838px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"adaptive-thresholding\"><strong>Adaptive Thresholding:<\/strong><\/h3>\n\n\n\n<p>In simple thresholding, the threshold value was global which means it was same for all the pixels in the image. But this may not be the best approach for thresholding as the different image sections can have different lightings. Thus we need Adaptive thresholding, which is the method where the threshold value is calculated for smaller regions and therefore, there will be different threshold values for different regions. In OpenCV we have adaptiveThreshold() function to implement this type of thresholding. Here is the syntax of this function:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nadaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C)\n<\/pre><\/div>\n\n\n<p>This method accepts the following parameters \u2212<\/p>\n\n\n\n<p>src \u2212 An object of the class Mat representing the source (input) image.<br>dst \u2212 An object of the class Mat representing the destination (output) image.<br>maxValue \u2212 A variable of double type representing the value that is to be given if pixel value is more than the threshold value.<br>adaptiveMethod \u2212 A variable of integer the type representing the adaptive method to be used. This will be either of the following two values:<br>cv.ADAPTIVE_THRESH_MEAN_C: The threshold value is the mean of the neighbourhood area minus the constant C.<br>cv.ADAPTIVE_THRESH_GAUSSIAN_C: The threshold value is a gaussian-weighted sum of the neighbourhood values minus the constant C.<\/p>\n\n\n\n<p>thresholdType \u2212 A variable of integer type representing the type of threshold to be used.<br>blockSize \u2212 A variable of the integer type representing size of the pixelneighborhood used to calculate the threshold value.<br>C \u2212 A variable of double type representing the constant used in the both methods (subtracted from the mean or weighted mean).<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2  \nimport numpy as np  \n  \n# path to input image is specified and   \n# image is loaded with imread command  \nimage = cv2.imread(&#039;lamp.jpg&#039;)  \n  \n\n# to convert the image in grayscale  \nimg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\nret, th1 = cv2.threshold(img,160, 255, cv2.THRESH_BINARY) \n  \nth2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\n            cv2.THRESH_BINARY,11,2)\nth3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n            cv2.THRESH_BINARY,11,2)\n\ncv2.imshow(&#039;Original&#039;,image)\ncv2.imshow(&#039;Binary Threshold&#039;, th1) \ncv2.imshow(&#039;Adaptive Threshold&#039;, th2) \ncv2.imshow(&#039;Gaussain Adaptive Threshold&#039;, th3) \n    \n# De-allocate any associated memory usage   \ncv2.waitKey(0)\ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres.png\"><img decoding=\"async\" width=\"950\" height=\"788\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres.png\" alt=\"OpenCV Tutorial\" class=\"wp-image-23257\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres.png 950w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres-300x249.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres-768x637.png 768w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres-696x577.png 696w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/adapthres-506x420.png 506w\" sizes=\"(max-width: 950px) 100vw, 950px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-contours\"><strong>OpenCV Contours<\/strong><\/h2>\n\n\n\n<p>So what are contours? A Contour is a curve joining all the continuous points having the same color or intensity (along the boundary).So the counters are useful especially when we want to find out a shape of some object or incase of object detection and recognition.<br><br>Finding contours is like finding white object from black background, so remember, the object to be found should be white and background should be black. Thus, for better accuracy, we should use binary images and before finding contours, apply thresholding as we discussed in the last section.<br><br> In OpenCV, we use two functions, one to find contours and other to draw contours. We use findContours() function to find contours and drawCounter() to draw one. Here is the syntax of these functions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nimage, contours, hierarchy=cv.findContours(img, mode, method,contours, hierarchy,offset)\n<\/pre><\/div>\n\n\n<p>This function returns three objects:<\/p>\n\n\n\n<p>Img:The input image in which we have to find contours<br>Contours: It contains detected contours and&nbsp; contour is stored as a vector of points<br>Hierarchy:Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i], the elements hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.<br>Parameters of this function:<\/p>\n\n\n\n<p>mode: Contour retrieval mode, see RetrievalModes<br>method:Contour approximation method, see ContourApproximationModes<br>offset : Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.<\/p>\n\n\n\n<p>Here is the syntax of drawCounter():<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv.drawContours(image, contours, contourIdx, color, thickness, lineType, hierarchy, maxLevel, offset)\n<\/pre><\/div>\n\n\n<p>Parameters<\/p>\n\n\n\n<p>Image: Input image.<br>contours: All the input contours. Each contour is stored as a point vector.<br>contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.<br>color: Color of the contours.<br>thickness: Thickness of lines the contours are drawn with. If it is negative (for example, thickness=FILLED ), the contour interiors are drawn.<br>lineType: Line connectivity. See <a href=\"https:\/\/docs.opencv.org\/3.4\/d0\/de1\/group__core.html#gaf076ef45de481ac96e0ab3dc2c29a777\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">LineTypes<\/a><br>hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see maxLevel ).<br>maxLevel: Maximal level for drawn contours. If it is 0, only the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is hierarchy available.<br>offset: Optional contour shift parameter. Shift all the drawn contours by the specified offset=(dx,dy).<\/p>\n\n\n\n<p>Here is an example using these functions:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2 \nimport numpy as np \n  \n# Let&#039;s load a simple image with 3 black squares \nimage = cv2.imread(&#039;contor.png&#039;,1) \n# Find Canny edges \nedged = cv2.Canny(image, 30, 200) \ncv2.waitKey(0) \n  \n# Finding Contours \n# Use a copy of the image e.g. edged.copy() \n# since findContours alters the image \ncontours, hierarchy = cv2.findContours(edged,  \n    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) \ncv2.imshow(&#039;Original&#039;, image) \ncv2.imshow(&#039;Canny Edges After Contouring&#039;, edged)  \n  \ncv2.drawContours(image, contours, -1, (0, 255, 0), 3) \n  \ncv2.imshow(&#039;Contours&#039;, image) \ncv2.waitKey(0) \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large td-caption-align-https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors.png zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors.png\"><img decoding=\"async\" width=\"1024\" height=\"277\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors-1024x277.png\" alt=\"OpenCV Tutorial\" class=\"wp-image-23259\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors-1024x277.png 1024w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors-300x81.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors-768x208.png 768w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors-696x188.png 696w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors-1068x289.png 1068w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/cotors.png 1428w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-mouse-event\"><strong>OpenCV Mouse Event<\/strong><\/h2>\n\n\n\n<p>OpenCV also provides the functionality to control and manage different types of mouse events and gives us the flexibility to manage them. As we know there can be different types of mouse events such as double_click, left button click, right button click, etc. <br><br>For managing these events, we need to design callback functions for each of these mouse click events while the window or frame is opened by OpenCV.The callback function gives us flexibility to implement what type of functionality you want with a particular mouse click event.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"mouse-as-a-paint-brush\"><strong>Mouse as a Paint Brush<\/strong><\/h3>\n\n\n\n<p>Using OpenCV in python , we have an option to use the mouse as a paint brush or a drawing tool. Whenever any mouse event occurs on the window screen, it gives us the coordinates (x,y) for that particular mouse event. Now that we have the coordinates of the point we are interested in, we can draw anything we desire, be it a circle or a rectangle or a simple line. First let us see the available mouse events, to get the list of all these events, run the code below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2  \nmouse_events = &#x5B;j for j in dir(cv2) if &#039;EVENT&#039; in j]  \nprint(mouse_events)  \n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n &#x5B;&#039;EVENT_FLAG_ALTKEY&#039;, &#039;EVENT_FLAG_CTRLKEY&#039;, &#039;EVENT_FLAG_LBUTTON&#039;, &#039;EVENT_FLAG_MBUTTON&#039;, &#039;EVENT_FLAG_RBUTTON&#039;, &#039;EVENT_FLAG_SHIFTKEY&#039;, &#039;EVENT_LBUTTONDBLCLK&#039;, &#039;EVENT_LBUTTONDOWN&#039;, &#039;EVENT_LBUTTONUP&#039;, &#039;EVENT_MBUTTONDBLCLK&#039;, &#039;EVENT_MBUTTONDOWN&#039;, &#039;EVENT_MBUTTONUP&#039;, &#039;EVENT_MOUSEHWHEEL&#039;, &#039;EVENT_MOUSEMOVE&#039;, &#039;EVENT_MOUSEWHEEL&#039;, &#039;EVENT_RBUTTONDBLCLK&#039;, &#039;EVENT_RBUTTONDOWN&#039;, &#039;EVENT_RBUTTONUP&#039;]   \n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"draw-circle\"><strong>Draw Circle<\/strong><\/h3>\n\n\n\n<p>To draw anything on the window screen, we first need to create a mouse callback function by using the cv2.setMouseCallback() function. It has a specific format that remains the same everywhere. Our mouse callback function is facilitated by drawing a circle using double-click. Here is the code:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2  \nimport numpy as np  \n# Creating mouse callback function  \ndef draw_circle(event,x,y,flags,param):  \n    if(event == cv2.EVENT_LBUTTONDBLCLK):  \n            cv2.circle(img,(x,y),50,(123,125, 200),-1)  \n# Creating a black image, a window and bind the function to window  \nimg = np.zeros((512,512,3), np.uint8)  \ncv2.namedWindow(&#039;image&#039;)  \ncv2.setMouseCallback(&#039;image&#039;,draw_circle)  \nwhile(1):  \n    cv2.imshow(&#039;image&#039;,img)  \n    if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n        break\n  \ncv2.destroyAllWindows()  \n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/draw-circle.png\"><img decoding=\"async\" width=\"640\" height=\"659\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/draw-circle.png\" alt=\"OpenCV Tutorial\" class=\"wp-image-23260\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/draw-circle.png 640w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/draw-circle-291x300.png 291w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/draw-circle-408x420.png 408w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-template-matching\"><strong>OpenCV Template Matching<\/strong><\/h2>\n\n\n\n<p>Template Matching is a method used for finding the location of a template image in a larger image. In OpenCV, we use a function cv.matchTemplate() for template matching. It simply slides the template image over the larger input image (as in 2D convolution) and compares the template image with the patch of input image under the template image. It returns a grayscale image, where each pixel denotes how much does the neighbourhood of that pixel match with the template. There are several comparison methods that can be implemented in OpenCV.&nbsp;<\/p>\n\n\n\n<p>If input image is of size (WxH) and template image is of size (wxh), output image will have a size of (W-w+1, H-h+1).Upon getting results, the best matches can be found as global minimums (when TM_SQDIFF was used) or maximums (when TM_CCORR or TM_CCOEFF was used) using the minMaxLoc function. Take it as the top-left corner of the rectangle and take (w,h) as width and height of the rectangle. That rectangle is your region of template.<\/p>\n\n\n\n<p>Here is the syntax of&nbsp; cv.matchTemplate():<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncv.matchTemplate(image, templ, method,mask)\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>image: Image where the search is running. It must be 8-bit or 32-bit floating-point.<br>templ: Searched template. It must be not greater than the source image and have the same data type.<br>result Map of comparison results. It must be single-channel 32-bit floating-point. If image is W\u00d7H and templ is w\u00d7h , then result is (W\u2212w+1)\u00d7(H\u2212h+1) .<br>method: Parameter specifying the comparison method, see <a href=\"https:\/\/docs.opencv.org\/master\/df\/dfb\/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">TemplateMatchModes<\/a><br>mask: Optional<\/p>\n\n\n\n<p>Here is an example in which we take this image as the template image:<\/p>\n\n\n<figure class=\"wp-block-image aligncenter size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/logo1.jpeg\"><img decoding=\"async\" width=\"88\" height=\"80\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/logo1.jpeg\" alt=\"\" class=\"wp-image-23263\"><\/figure>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimg = cv.imread(&#039;headphone1.jpeg&#039;,0)\nimg2 = img.copy()\ntemplate = cv.imread(&#039;logo1.jpeg&#039;,0)\nw, h = template.shape&#x5B;::-1]\n# All the 6 methods for comparison in a list\n# Apply template Matching\nres = cv.matchTemplate(img,template,eval(&#039;cv.TM_CCOEFF&#039;))\nmin_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)\n# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\ntop_left = max_loc\nbottom_right = (top_left&#x5B;0] + w, top_left&#x5B;1] + h)\ncv.rectangle(img,top_left, bottom_right, 255, 2)\nplt.subplot(121),plt.imshow(res,cmap = &#039;gray&#039;)\nplt.title(&#039;Matching Result&#039;), plt.xticks(&#x5B;]), plt.yticks(&#x5B;])\nplt.subplot(122),plt.imshow(img,cmap = &#039;gray&#039;)\nplt.title(&#039;Detected Point&#039;), plt.xticks(&#x5B;]), plt.yticks(&#x5B;])\nplt.show()\n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-matcing.png\"><img decoding=\"async\" width=\"620\" height=\"531\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-matcing.png\" alt=\"OpenCV Tutorial\" class=\"wp-image-23261\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-matcing.png 620w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-matcing-300x257.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-matcing-490x420.png 490w\" sizes=\"(max-width: 620px) 100vw, 620px\" \/><\/figure>\n\n\n\n<p><strong>Template Matching with Multiple Objects<\/strong><\/p>\n\n\n\n<p>In the above example, we searched for template images that occurred only once in the image. Suppose a particular object occurs multiple times in a particular image. In this scenario, we will use the thresholding as cv2.minMaxLoc() just gives the location of one template image and it won't give all locations of the template images. Consider the following example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimg2=cv.imread(&#039;headohone2.jpeg&#039;,1)\nimg_gray = cv.imread(&#039;headohone2.jpeg&#039;,0)\ntemplate = cv.imread(&#039;logo1.jpeg&#039;,0)\nw, h = template.shape&#x5B;::-1]\nres = cv.matchTemplate(img_gray,template,eval(&#039;cv.TM_CCOEFF_NORMED&#039;))\nprint(res)\nthreshold = 0.52\nloc = np.where( res &gt;= threshold)\nfor pt in zip(*loc&#x5B;::-1]):\n    cv.rectangle(img2, pt, (pt&#x5B;0] + w, pt&#x5B;1] + h), (255,0,0), 1)\nplt.subplot(121),plt.imshow(res,cmap = &#039;gray&#039;)\nplt.title(&#039;Matching Result&#039;), plt.xticks(&#x5B;]), plt.yticks(&#x5B;])\nplt.subplot(122),plt.imshow(img2,cmap = &#039;gray&#039;)\nplt.title(&#039;Detected Point&#039;), plt.xticks(&#x5B;]), plt.yticks(&#x5B;])\nplt.show()\n<\/pre><\/div>\n\n<figure class=\"wp-block-image size-large zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-2.png\"><img decoding=\"async\" width=\"628\" height=\"523\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-2.png\" alt=\"OpenCV Tutorial\" class=\"wp-image-23262\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-2.png 628w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-2-300x250.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/12\/template-2-504x420.png 504w\" sizes=\"(max-width: 628px) 100vw, 628px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"opencv-video-capture\"><strong>OpenCV Video Capture<\/strong><\/h2>\n\n\n\n<p>OpenCV can also be used for video processing. With OpenCV, we can capture a video from the camera and it also lets us create a video capture object which is helpful to capture videos through webcam and then you may perform desired operations on that video. Besides this you can also play and perform operation on a video file and save them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"capture-video-from-camera\"><strong>Capture Video from Camera<\/strong><\/h3>\n\n\n\n<p>Often, we have to capture a live stream with a camera. Using OpenCV\u2019s very simple interface, we can easily do it. Here is a simple task to get started. In this task we will capture a video from the camera ( in-built webcam of my laptop) and display it as a grayscale video.<\/p>\n\n\n\n<p>In OpenCV we need to create a VideoCapture object to capture a video. We pass either the device index or the name of a video file as its arguments. Device index is just the number to specify the camera in case we have multiple webcams available. Normally one has only a single camera connected (as in my case), so simply pass 0.After this we start to capture each frame using a loop and process it accordingly. At the end, we just break from the loop and release the capture.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport cv2\n\ncapture = cv2.VideoCapture(0)\n\nwhile(True):\n    # Capture frame-by-frame\n    ret, frame = cap.read()\n\n    # Our operations on the frame come here\n    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n    # Display the resulting frame\n    cv2.imshow(&#039;frame&#039;,gray)\n    if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n        break\n\n# When everything done, release the capture\ncapture.release()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<p>capture.read() returns a bool (True\/False) and the frame which webcam is currently reading. If the frame is read correctly, it will be True. So you can check the end of the video by checking this return value.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"playing-video-from-file\"><strong>Playing Video from file<\/strong><\/h3>\n\n\n\n<p>Playing a video using OpenCV in python is very similar to capturing live feed from a webcam as we saw in the last section.We just have to change the camera index with the video file name. But sometimes the video file may be corrupt or couldn't be read properly,so we use isOpened() method of VideoCapture object to make sure that the video is read successfully. Also, while displaying the frame, we should use appropriate time for cv2.waitKey(),as for too less, video will be very fast and for too high values, video will be slow.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(&#039;vtest.avi&#039;)\n\nwhile(cap.isOpened()):\n    ret, frame = cap.read()\n\n    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n    cv2.imshow(&#039;frame&#039;,gray)\n    if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n        break\n\ncap.release()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"saving-a-video\"><strong>Saving a Video<\/strong><\/h3>\n\n\n\n<p>Saving an image after processing it using OpenCV is quite simple and we saw how to do it using cv2.imwrite() function. But for a video, after processing it frame-by-frame a little more work is required to save it.<\/p>\n\n\n\n<p>Here to save a video we create a VideoWriter object in addition to VideoCapture Object. The syntax of VideoWriter is given below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncv2.VideoWriter(filename,fourcc,fps,frameSize,isColor)\n<\/pre><\/div>\n\n\n<p>Parameters:<\/p>\n\n\n\n<p>filename: The output file name (eg: bday.avi).<br>fourcc: specify the FourCC code. FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org. It is platform dependent. Following codecs works fine for me.<\/p>\n\n\n\n<p>In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video)<br>In Windows: DIVX (More to be tested and added)<br>In OSX : (I don\u2019t have access to OSX. Can some one fill this?)<br>FourCC code is passed as cv2.VideoWriter_fourcc('M','J','P','G') or cv2.VideoWriter_fourcc(*'MJPG) for MJPG.<\/p>\n\n\n\n<p>fps: number of frames per second (fps)&nbsp;<br>frameSize: size of frame.&nbsp;<br>isColor: It is a flag value. If it is True, encoders expect a color frame, otherwise it works with grayscale frames.<\/p>\n\n\n\n<p>Here is a code that captures frames from a Camera, flip each one in a vertical direction and save it.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\n# Define the codec and create VideoWriter object\nfourcc = cv2.VideoWriter_fourcc(*&#039;XVID&#039;)\nout = cv2.VideoWriter(&#039;output.avi&#039;,fourcc, 20.0, (640,480))\n\nwhile(cap.isOpened()):\n    ret, frame = cap.read()\n    if ret==True:\n        frame = cv2.flip(frame,0)\n\n        # write the flipped frame\n        out.write(frame)\n\n        cv2.imshow(&#039;frame&#039;,frame)\n        if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n            break\n    else:\n        break\n\n# Release everything if job is finished\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"face-detection-using-opencv\"><strong>Face Detection Using OpenCV<\/strong><\/h2>\n\n\n\n<p>Using OpenCV, complex tasks such as face detection becomes easy to implement and since pre-trained models that are capable of detecting faces, noses, and eyes are included in the OpenCV package, we don't need to train any classifier. Here is an article on<a href=\"https:\/\/www.mygreatlearning.com\/blog\/viola-jones-algorithm\/\" target=\"_blank\" rel=\"noreferrer noopener\"> Face detection using Viola-Jones algorithm<\/a> that explains how we can detect faces using OpenCV.You will also go through the concept of cascading classifier in this article that is also used in our next section i.e. car detection using OpenCV<br><\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/youtu.be\/6myMFJl8CbA\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"car-detection-with-opencv\"><strong>Car detection with OpenCV<\/strong><\/h2>\n\n\n\n<p>You may have seen in the article Face detection using Face Recognition Using Python and OpenCV Viola-Jones algorithm that we used pre-trained models to detect faces and eyes. Similarly, we also have a pre-trained model that can detect cars. All we have to do is to use this model to erect cars and then mark the cars with rectangles.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# OpenCV Python program to detect cars in video frame \n# import libraries of python OpenCV  \nimport cv2 \n  \n# capture frames from a video \ncap = cv2.VideoCapture(&#039;video.avi&#039;) \n  \n# Trained XML classifiers describes some features of some object we want to detect \ncar_cascade = cv2.CascadeClassifier(&#039;cars.xml&#039;) \n  \n# loop runs if capturing has been initialized. \nwhile True: \n    # reads frames from a video \n    ret, frames = cap.read() \n      \n    # convert to gray scale of each frames \n    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY) \n      \n  \n    # Detects cars of different sizes in the input image \n    cars = car_cascade.detectMultiScale(gray, 1.1, 1) \n      \n    # To draw a rectangle in each cars \n    for (x,y,w,h) in cars: \n        cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2) \n  \n   # Display frames in a window  \n   cv2.imshow(&#039;video2&#039;, frames) \n      \n    # Wait for Esc key to stop \n    if cv2.waitKey(33) == 27: \n        break\n  \n# De-allocate any associated memory usage \ncv2.destroyAllWindows() \n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"face-recognition-using-opencv\"><strong>Face Recognition Using OpenCV<\/strong><\/h2>\n\n\n\n<p>Face recognition, as the names suggest includes detecting faces and then label them with the name of the person. It is a bit more complex than the last two examples. Here we have to use some libraries outside of OpenCV. I would highly recommend going through the article <a href=\"https:\/\/www.mygreatlearning.com\/blog\/face-recognition\/\" target=\"_blank\" rel=\"noreferrer noopener\">Face Recognition Using Python and OpenCV<\/a> to understand face recognition works and how to implement it using OpenCV.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"wrapping-up\">Wrapping Up<\/h2>\n\n\n\n<p>In conclusion, this OpenCV tutorial has provided a comprehensive guide to learning OpenCV in Python, equipping you with essential skills for image processing and computer vision tasks. <br><br>If you're interested in expanding your Python proficiency, consider exploring Great Learning's Free Python courses. Designed to cater to beginners and advanced learners alike, these courses offer structured learning paths to master Python programming. <br><br>Additionally, our <a href=\"https:\/\/www.mygreatlearning.com\/software-engineering\/courses\">Software Development Course<\/a> provides in-depth training in software engineering principles and practices, ideal for those aspiring to build a career in software development. <br><br>With an industry-relevant curriculum and hands-on projects, our courses empower you to excel in the dynamic technology field with the most demanded skills and expertise.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faqs-of-opencv-in-python\"><strong>FAQs of OpenCV In Python<\/strong><\/h2>\n\n\n\n<div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1715678238456\"><strong class=\"schema-faq-question\"><strong>Q. What is OpenCV in python?<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A.<\/strong>OpenCV in python is an open-source computer vision and machine learning software library. It was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678250948\"><strong class=\"schema-faq-question\"><strong>Q.How to install OpenCV?<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> To install OpenCV 3.0 and Python 3.4+ on Ubuntu, you need to follow the steps mentioned below:<br\/>Start with installing prerequisites<br\/>Now Setup Python (Part 1)\u00a0<br\/>Setup Python (Part 2)\u00a0<br\/>Now you need to build and install OpenCV 3.0 with Python 3.4+ bindings<br\/>Sym-link OpenCV 3.0<br\/>The last step includes testing out the OpenCV 3.0 and Python 3.4+ install.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678287300\"><strong class=\"schema-faq-question\"><strong>Q: How do I start learning OpenCV?\u00a0<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> To start learning OpenCV, you can refer to the tutorials offered by Great Learning. You will not only learn the basics and also get a good idea of the overall OpenCV.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678297474\"><strong class=\"schema-faq-question\"><strong>Q: What is the full form of OpenCV?\u00a0<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> The full form for OpenCV is Open Source Computer Vision Library.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678311354\"><strong class=\"schema-faq-question\"><strong>Q: Why is OpenCV used?\u00a0<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> OpenCV is a vast open-source library that is used for machine learning, computer vision, and image processing. At present, it plays a key role in real-time. Using OpenCV helps in processing images as well as videos to classify faces, objects, or even handwriting of humans.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678322298\"><strong class=\"schema-faq-question\"><strong>Q: Is OpenCV easy?\u00a0<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> Earlier OpenCV was not one of the easiest things to learn. However, these days it has been simplified. You can go through the easy-to-learn tutorials to understand OpenCV.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678323880\"><strong class=\"schema-faq-question\"><strong>Q: Is OpenCV better in Python or C++?\u00a0<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> It totally depends on the stage of a project. If you are prototyping, Python is more useful. If it is for the purpose of production, C++ is better. However, you also need to know that Python is slower than C++.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678325166\"><strong class=\"schema-faq-question\"><strong>Q: Is OpenCV worth learning?\u00a0<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> Learning OpenCV is certainly worth it, and you should start learning OpenCV with Python. This programming language is easier to learn and faster to prototype the Computer Vision algorithms.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678367426\"><strong class=\"schema-faq-question\"><strong>Q: What should I learn before OpenCV?<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> It is a library; therefore you first need to know how to use a library. The next thing is learning the fundamentals of image processing. You also need to have in-depth knowledge of classes and inheritance in C++.<br\/><\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1715678380694\"><strong class=\"schema-faq-question\"><strong>Q: How do I know if Opencv is installed?<\/strong><\/strong> <p class=\"schema-faq-answer\"><strong>A:<\/strong> First fire up your Python and follow the commands mentioned below:<br\/>Importing cv2 # import the opencv library, and<br\/>cv2. __version__ #. This will help in printing the version of your opencv3.<\/p> <\/div> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>OpenCV is a widely acclaimed open-source library that provides an extensive suite of computer vision and image processing functions. It offers a vast array of tools and techniques that empower developers to build cutting-edge applications in fields like robotics, augmented reality, facial recognition, object detection, and much more. With its powerful capabilities and user-friendly interface, [&hellip;]<\/p>\n","protected":false},"author":41,"featured_media":23138,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[2],"tags":[],"content_type":[36248],"class_list":["post-23005","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-artificial-intelligence","content_type-career-guide"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>OpenCV Tutorial: A Guide to Learn OpenCV in Python<\/title>\n<meta name=\"description\" content=\"OpenCV Python Tutorial: OpenCV (Open Source Computer Vision Library) is an open source software library for computer vision.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"OpenCV Tutorial: A Guide to Learn OpenCV in Python\" \/>\n<meta property=\"og:description\" content=\"OpenCV Python Tutorial: OpenCV (Open Source Computer Vision Library) is an open source software library for computer vision.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"Great Learning Blog: Free Resources what Matters to shape your Career!\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/GreatLearningOfficial\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-04-09T05:22:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-09-02T11:31:32+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"724\" \/>\n\t<meta property=\"og:image:height\" content=\"483\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Great Learning Editorial Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/Great_Learning\" \/>\n<meta name=\"twitter:site\" content=\"@Great_Learning\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Great Learning Editorial Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"36 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/\"},\"author\":{\"name\":\"Great Learning Editorial Team\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\"},\"headline\":\"OpenCV Tutorial: A Guide to Learn OpenCV in Python\",\"datePublished\":\"2024-04-09T05:22:00+00:00\",\"dateModified\":\"2024-09-02T11:31:32+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/\"},\"wordCount\":7370,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/11\\\/iStock-898172160.jpg\",\"articleSection\":[\"AI and Machine Learning\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#respond\"]}]},{\"@type\":[\"WebPage\",\"FAQPage\"],\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/\",\"name\":\"OpenCV Tutorial: A Guide to Learn OpenCV in Python\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/11\\\/iStock-898172160.jpg\",\"datePublished\":\"2024-04-09T05:22:00+00:00\",\"dateModified\":\"2024-09-02T11:31:32+00:00\",\"description\":\"OpenCV Python Tutorial: OpenCV (Open Source Computer Vision Library) is an open source software library for computer vision.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#breadcrumb\"},\"mainEntity\":[{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678238456\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678250948\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678287300\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678297474\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678311354\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678322298\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678323880\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678325166\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678367426\"},{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678380694\"}],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/11\\\/iStock-898172160.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/11\\\/iStock-898172160.jpg\",\"width\":724,\"height\":483,\"caption\":\"opencv tutorial\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Blog\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"AI and Machine Learning\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/artificial-intelligence\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"OpenCV Tutorial: A Guide to Learn OpenCV in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"name\":\"Great Learning Blog\",\"description\":\"Learn, Upskill &amp; Career Development Guide and Resources\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"alternateName\":\"Great Learning\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\",\"name\":\"Great Learning\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"width\":900,\"height\":900,\"caption\":\"Great Learning\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/GreatLearningOfficial\\\/\",\"https:\\\/\\\/x.com\\\/Great_Learning\",\"https:\\\/\\\/www.instagram.com\\\/greatlearningofficial\\\/\",\"https:\\\/\\\/www.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/in.pinterest.com\\\/greatlearning12\\\/\",\"https:\\\/\\\/www.youtube.com\\\/user\\\/beaconelearning\\\/\"],\"description\":\"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.\",\"email\":\"info@mygreatlearning.com\",\"legalName\":\"Great Learning Education Services Pvt. Ltd\",\"foundingDate\":\"2013-11-29\",\"numberOfEmployees\":{\"@type\":\"QuantitativeValue\",\"minValue\":\"1001\",\"maxValue\":\"5000\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\",\"name\":\"Great Learning Editorial Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"caption\":\"Great Learning Editorial Team\"},\"description\":\"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.\",\"sameAs\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/\",\"https:\\\/\\\/in.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/Great_Learning\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCObs0kLIrDjX2LLSybqNaEA\"],\"award\":[\"Best EdTech Company of the Year 2024\",\"Education Economictimes Outstanding Education\\\/Edtech Solution Provider of the Year 2024\",\"Leading E-learning Platform 2024\"],\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/author\\\/greatlearning\\\/\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678238456\",\"position\":1,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678238456\",\"name\":\"Q. What is OpenCV in python?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A.<\\\/strong>OpenCV in python is an open-source computer vision and machine learning software library. It was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678250948\",\"position\":2,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678250948\",\"name\":\"Q.How to install OpenCV?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> To install OpenCV 3.0 and Python 3.4+ on Ubuntu, you need to follow the steps mentioned below:<br\\\/>Start with installing prerequisites<br\\\/>Now Setup Python (Part 1)\u00a0<br\\\/>Setup Python (Part 2)\u00a0<br\\\/>Now you need to build and install OpenCV 3.0 with Python 3.4+ bindings<br\\\/>Sym-link OpenCV 3.0<br\\\/>The last step includes testing out the OpenCV 3.0 and Python 3.4+ install.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678287300\",\"position\":3,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678287300\",\"name\":\"Q: How do I start learning OpenCV?\u00a0\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> To start learning OpenCV, you can refer to the tutorials offered by Great Learning. You will not only learn the basics and also get a good idea of the overall OpenCV.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678297474\",\"position\":4,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678297474\",\"name\":\"Q: What is the full form of OpenCV?\u00a0\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> The full form for OpenCV is Open Source Computer Vision Library.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678311354\",\"position\":5,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678311354\",\"name\":\"Q: Why is OpenCV used?\u00a0\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> OpenCV is a vast open-source library that is used for machine learning, computer vision, and image processing. At present, it plays a key role in real-time. Using OpenCV helps in processing images as well as videos to classify faces, objects, or even handwriting of humans.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678322298\",\"position\":6,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678322298\",\"name\":\"Q: Is OpenCV easy?\u00a0\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> Earlier OpenCV was not one of the easiest things to learn. However, these days it has been simplified. You can go through the easy-to-learn tutorials to understand OpenCV.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678323880\",\"position\":7,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678323880\",\"name\":\"Q: Is OpenCV better in Python or C++?\u00a0\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> It totally depends on the stage of a project. If you are prototyping, Python is more useful. If it is for the purpose of production, C++ is better. However, you also need to know that Python is slower than C++.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678325166\",\"position\":8,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678325166\",\"name\":\"Q: Is OpenCV worth learning?\u00a0\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> Learning OpenCV is certainly worth it, and you should start learning OpenCV with Python. This programming language is easier to learn and faster to prototype the Computer Vision algorithms.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678367426\",\"position\":9,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678367426\",\"name\":\"Q: What should I learn before OpenCV?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> It is a library; therefore you first need to know how to use a library. The next thing is learning the fundamentals of image processing. You also need to have in-depth knowledge of classes and inheritance in C++.<br\\\/>\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678380694\",\"position\":10,\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/opencv-tutorial-in-python\\\/#faq-question-1715678380694\",\"name\":\"Q: How do I know if Opencv is installed?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"<strong>A:<\\\/strong> First fire up your Python and follow the commands mentioned below:<br\\\/>Importing cv2 # import the opencv library, and<br\\\/>cv2. __version__ #. This will help in printing the version of your opencv3.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"OpenCV Tutorial: A Guide to Learn OpenCV in Python","description":"OpenCV Python Tutorial: OpenCV (Open Source Computer Vision Library) is an open source software library for computer vision.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/","og_locale":"en_US","og_type":"article","og_title":"OpenCV Tutorial: A Guide to Learn OpenCV in Python","og_description":"OpenCV Python Tutorial: OpenCV (Open Source Computer Vision Library) is an open source software library for computer vision.","og_url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/","og_site_name":"Great Learning Blog: Free Resources what Matters to shape your Career!","article_publisher":"https:\/\/www.facebook.com\/GreatLearningOfficial\/","article_published_time":"2024-04-09T05:22:00+00:00","article_modified_time":"2024-09-02T11:31:32+00:00","og_image":[{"width":724,"height":483,"url":"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg","type":"image\/jpeg"}],"author":"Great Learning Editorial Team","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/Great_Learning","twitter_site":"@Great_Learning","twitter_misc":{"Written by":"Great Learning Editorial Team","Est. reading time":"36 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#article","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/"},"author":{"name":"Great Learning Editorial Team","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad"},"headline":"OpenCV Tutorial: A Guide to Learn OpenCV in Python","datePublished":"2024-04-09T05:22:00+00:00","dateModified":"2024-09-02T11:31:32+00:00","mainEntityOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/"},"wordCount":7370,"commentCount":0,"publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg","articleSection":["AI and Machine Learning"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#respond"]}]},{"@type":["WebPage","FAQPage"],"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/","url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/","name":"OpenCV Tutorial: A Guide to Learn OpenCV in Python","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#primaryimage"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg","datePublished":"2024-04-09T05:22:00+00:00","dateModified":"2024-09-02T11:31:32+00:00","description":"OpenCV Python Tutorial: OpenCV (Open Source Computer Vision Library) is an open source software library for computer vision.","breadcrumb":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#breadcrumb"},"mainEntity":[{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678238456"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678250948"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678287300"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678297474"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678311354"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678322298"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678323880"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678325166"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678367426"},{"@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678380694"}],"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#primaryimage","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg","width":724,"height":483,"caption":"opencv tutorial"},{"@type":"BreadcrumbList","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog","item":"https:\/\/www.mygreatlearning.com\/blog\/"},{"@type":"ListItem","position":2,"name":"AI and Machine Learning","item":"https:\/\/www.mygreatlearning.com\/blog\/artificial-intelligence\/"},{"@type":"ListItem","position":3,"name":"OpenCV Tutorial: A Guide to Learn OpenCV in Python"}]},{"@type":"WebSite","@id":"https:\/\/www.mygreatlearning.com\/blog\/#website","url":"https:\/\/www.mygreatlearning.com\/blog\/","name":"Great Learning Blog","description":"Learn, Upskill &amp; Career Development Guide and Resources","publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"alternateName":"Great Learning","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.mygreatlearning.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization","name":"Great Learning","url":"https:\/\/www.mygreatlearning.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","width":900,"height":900,"caption":"Great Learning"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/GreatLearningOfficial\/","https:\/\/x.com\/Great_Learning","https:\/\/www.instagram.com\/greatlearningofficial\/","https:\/\/www.linkedin.com\/school\/great-learning\/","https:\/\/in.pinterest.com\/greatlearning12\/","https:\/\/www.youtube.com\/user\/beaconelearning\/"],"description":"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.","email":"info@mygreatlearning.com","legalName":"Great Learning Education Services Pvt. Ltd","foundingDate":"2013-11-29","numberOfEmployees":{"@type":"QuantitativeValue","minValue":"1001","maxValue":"5000"}},{"@type":"Person","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad","name":"Great Learning Editorial Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","caption":"Great Learning Editorial Team"},"description":"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.","sameAs":["https:\/\/www.mygreatlearning.com\/","https:\/\/in.linkedin.com\/school\/great-learning\/","https:\/\/x.com\/https:\/\/twitter.com\/Great_Learning","https:\/\/www.youtube.com\/channel\/UCObs0kLIrDjX2LLSybqNaEA"],"award":["Best EdTech Company of the Year 2024","Education Economictimes Outstanding Education\/Edtech Solution Provider of the Year 2024","Leading E-learning Platform 2024"],"url":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678238456","position":1,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678238456","name":"Q. What is OpenCV in python?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A.<\/strong>OpenCV in python is an open-source computer vision and machine learning software library. It was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678250948","position":2,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678250948","name":"Q.How to install OpenCV?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> To install OpenCV 3.0 and Python 3.4+ on Ubuntu, you need to follow the steps mentioned below:<br\/>Start with installing prerequisites<br\/>Now Setup Python (Part 1)\u00a0<br\/>Setup Python (Part 2)\u00a0<br\/>Now you need to build and install OpenCV 3.0 with Python 3.4+ bindings<br\/>Sym-link OpenCV 3.0<br\/>The last step includes testing out the OpenCV 3.0 and Python 3.4+ install.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678287300","position":3,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678287300","name":"Q: How do I start learning OpenCV?\u00a0","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> To start learning OpenCV, you can refer to the tutorials offered by Great Learning. You will not only learn the basics and also get a good idea of the overall OpenCV.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678297474","position":4,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678297474","name":"Q: What is the full form of OpenCV?\u00a0","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> The full form for OpenCV is Open Source Computer Vision Library.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678311354","position":5,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678311354","name":"Q: Why is OpenCV used?\u00a0","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> OpenCV is a vast open-source library that is used for machine learning, computer vision, and image processing. At present, it plays a key role in real-time. Using OpenCV helps in processing images as well as videos to classify faces, objects, or even handwriting of humans.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678322298","position":6,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678322298","name":"Q: Is OpenCV easy?\u00a0","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> Earlier OpenCV was not one of the easiest things to learn. However, these days it has been simplified. You can go through the easy-to-learn tutorials to understand OpenCV.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678323880","position":7,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678323880","name":"Q: Is OpenCV better in Python or C++?\u00a0","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> It totally depends on the stage of a project. If you are prototyping, Python is more useful. If it is for the purpose of production, C++ is better. However, you also need to know that Python is slower than C++.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678325166","position":8,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678325166","name":"Q: Is OpenCV worth learning?\u00a0","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> Learning OpenCV is certainly worth it, and you should start learning OpenCV with Python. This programming language is easier to learn and faster to prototype the Computer Vision algorithms.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678367426","position":9,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678367426","name":"Q: What should I learn before OpenCV?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> It is a library; therefore you first need to know how to use a library. The next thing is learning the fundamentals of image processing. You also need to have in-depth knowledge of classes and inheritance in C++.<br\/>","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678380694","position":10,"url":"https:\/\/www.mygreatlearning.com\/blog\/opencv-tutorial-in-python\/#faq-question-1715678380694","name":"Q: How do I know if Opencv is installed?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"<strong>A:<\/strong> First fire up your Python and follow the commands mentioned below:<br\/>Importing cv2 # import the opencv library, and<br\/>cv2. __version__ #. This will help in printing the version of your opencv3.","inLanguage":"en-US"},"inLanguage":"en-US"}]}},"uagb_featured_image_src":{"full":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",724,483,false],"thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160-150x150.jpg",150,150,true],"medium":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160-300x200.jpg",300,200,true],"medium_large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",724,483,false],"large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",724,483,false],"1536x1536":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",724,483,false],"2048x2048":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",724,483,false],"web-stories-poster-portrait":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",640,427,false],"web-stories-publisher-logo":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",96,64,false],"web-stories-thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/11\/iStock-898172160.jpg",150,100,false]},"uagb_author_info":{"display_name":"Great Learning Editorial Team","author_link":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"},"uagb_comment_info":0,"uagb_excerpt":"OpenCV is a widely acclaimed open-source library that provides an extensive suite of computer vision and image processing functions. It offers a vast array of tools and techniques that empower developers to build cutting-edge applications in fields like robotics, augmented reality, facial recognition, object detection, and much more. With its powerful capabilities and user-friendly interface,&hellip;","_links":{"self":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/23005","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/users\/41"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/comments?post=23005"}],"version-history":[{"count":79,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/23005\/revisions"}],"predecessor-version":[{"id":111106,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/23005\/revisions\/111106"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media\/23138"}],"wp:attachment":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media?parent=23005"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/categories?post=23005"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/tags?post=23005"},{"taxonomy":"content_type","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/content_type?post=23005"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}