<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[programming_fever - Medium]]></title>
        <description><![CDATA[A Medium publication sharing  projects,concepts,tips and tricks for python programming. - Medium]]></description>
        <link>https://medium.com/programming-fever?source=rss----7b66c578b334---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>programming_fever - Medium</title>
            <link>https://medium.com/programming-fever?source=rss----7b66c578b334---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/programming-fever" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Draw Using a Virtual Pen on a Computer Screen using OpenCV in Python]]></title>
            <link>https://medium.com/programming-fever/draw-using-a-virtual-pen-on-a-computer-screen-using-opencv-in-python-71d3a1d5902b?source=rss----7b66c578b334---4</link>
            <guid isPermaLink="false">https://medium.com/p/71d3a1d5902b</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Praveen]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 06:57:30 GMT</pubDate>
            <atom:updated>2020-08-01T09:12:52.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*lvnIOZ1pbL4S6zpuSGbdRg.png" /></figure><p>In this project, I use<strong> OpenCV </strong>in<strong> </strong>python to <strong>draw</strong> on the screen using a<strong> virtual pen</strong> i.e, any marker can be used to<strong> draw </strong>using the technique of <strong>contour detection</strong> based on the<strong> mask </strong>of the desired <strong>colored target</strong> marker.If you are a beginner and want to impress your friends with a visual demo, this is for you.</p><p><strong>Have a look at the final project in action:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhEzhSwVDqdQ&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhEzhSwVDqdQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff4039d1f2cbaf472e445df055d12249/href">https://medium.com/media/ff4039d1f2cbaf472e445df055d12249/href</a></iframe><p>If you want to jump straight into the code without explanation then you can scroll down to the bottom of this page, where the complete code is provided or <a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/Virtual%20Pen"><strong><em>click here for GitHub link</em></strong></a><strong><em>.</em></strong></p><h3>Steps involved</h3><h4><strong>Step 1:</strong></h4><p>Find the <strong>HSV range</strong> of the target <strong>Marker/pen </strong>and save the values in a .npy file</p><h4><strong>Step 2:</strong></h4><ul><li>First, we will use color masking to<strong> get a mask of our colored pen/marker</strong> using the above HSV range.</li><li>Next, using <strong>contour detection</strong> we detect and track the location of that pen,i.e get the<strong> x,y coordinates</strong>.</li><li>Next, <strong>draw a line </strong>by joining the x,y coordinates of pen’s <strong>previous location</strong> (<em>location in the previous frame</em>) with the<strong> new x,y points.</strong></li><li>Finally, add another<strong> feature to clear the entire Canvas</strong>/Screen.</li></ul><h3>Step 1: Find Color range of target Pen and save it</h3><p><a href="https://medium.com/@l.k.pravee/how-to-find-hsv-range-of-an-object-for-computer-vision-applications-254a8eb039fc">How to find HSV range of an Object for Computer Vision applications?</a></p><p>First and foremost we must find an appropriate color range for our target colored object, this range will be used in cv2.inrange() function to filter out our object. We will also save our range array as a .npy file in our disk so we can access it later.</p><p>Since we are trying to go for color detection we will convert our RGB (or BGR in OpenCV) format image to HSV (Hue, Saturation, Value) color format as its much easier to manipulate colors in that model.</p><p>This below script will let you use track bars to adjust the hue, saturation, and value channels of the image. Adjust the track bars until only your target object is visible and the rest is black.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26177418b14de0b33120a2b3ae127384/href">https://medium.com/media/26177418b14de0b33120a2b3ae127384/href</a></iframe><h3><strong>Step 2: start drawing</strong></h3><p>This entire application is built fundamentally on contour detection. It can be thought of as something like closed color curves on compromises that have the same color or intensity, it’s like a blob. In this project we use color masking to get the binary mask of our target color pen, then we use the counter detection to find the location of this pen and the contour to find it.</p><p>When we work with it then it is a matter of literally connecting the dots, we just have to draw a line using the x, y dots of the previous position of the pen with new x, y dots and that’s it. , We have a virtual pen.</p><p>There are 3 main points in the code</p><ol><li>Apply morphological operations.</li><li>Detect and track the colored object.</li><li>Find the object’s x,y coordinates.</li></ol><h4><strong>imports</strong></h4><pre>import cv2<br>import numpy as np<br>import time</pre><h4>loading HSV value , capturing video and initializing the required parameters</h4><pre>#This variable determines if we want to load color range from #memory or use the ones defined here.<br>load_from_disk = True</pre><pre># If true then load color range from memory<br>if load_from_disk:<br>    hsv_value = np.load(&#39;hsv_value.npy&#39;)</pre><pre>cap = cv2.VideoCapture(0)<br>cap.set(3,1280)<br>cap.set(4,720)</pre><pre>kernel = np.ones((5,5),np.uint8)</pre><pre># Initializing the canvas on which we will draw upon<br>canvas = None</pre><pre># Initilize x1,y1 points<br>x1,y1=0,0</pre><pre># Threshold for noise<br>noiseth = 800</pre><h4>Read video and a Apply morphological operations</h4><pre>while(1):<br>    _, frame = cap.read()<br>    frame = cv2.flip( frame, 1 )<br>    <br>    # Initialize the canvas as a black image of the same size as the frame.<br>    if canvas is None:<br>        canvas = np.zeros_like(frame)</pre><pre># Convert BGR to HSV<br>    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)<br>    <br>    # If you&#39;re reading from memory then load the upper and lower ranges <br>    # from there<br>    if load_from_disk:<br>        lower_range = hsv_value[0]<br>        upper_range = hsv_value[1]<br>            <br>    # Otherwise define your own custom values for upper and lower range.<br>    else:           <br>        lower_range  = np.array([134, 20, 204])<br>        upper_range = np.array([179, 255, 255])<br>    <br>    mask = cv2.inRange(hsv, lower_range, upper_range)<br>    <br>    # Perform morphological operations to get rid of the noise<br>    mask = cv2.erode(mask,kernel,iterations = 1)<br>    mask = cv2.dilate(mask,kernel,iterations = 2)</pre><h4>Find the object’s x,y coordinates and start drawing</h4><pre># Find Contours<br>    contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)<br>    <br>    # Make sure there is a contour present and also its size is bigger than <br>    # the noise threshold.<br>    if contours and cv2.contourArea(max(contours, <br>                                 key = cv2.contourArea)) &gt; noiseth:<br>                <br>        c = max(contours, key = cv2.contourArea)    <br>        x2,y2,w,h = cv2.boundingRect(c)<br>        <br>        # If there were no previous points then save the detected x2,y2 <br>        # coordinates as x1,y1. <br>        # This is true when we writing for the first time or when writing <br>        # again when the pen had disappeared from view.<br>        if x1 == 0 and y1 == 0:<br>            x1,y1= x2,y2<br>            <br>        else:<br>            # Draw the line on the canvas<br>            canvas = cv2.line(canvas, (x1,y1),(x2,y2), [255,0,0], 4)<br>        <br>        # After the line is drawn the new points become the previous points.<br>        x1,y1= x2,y2</pre><pre>    else:<br>        # If there were no contours detected then make x1,y1 = 0<br>        x1,y1 =0,0<br>    <br>    # Merge the canvas and the frame.<br>    frame = cv2.add(frame,canvas)<br>    <br>    # Optionally stack both frames and show it.<br>    stacked = np.hstack((canvas,frame))<br>    cv2.imshow(&#39;VIRTUAL PEN&#39;,cv2.resize(stacked,None,fx=0.6,fy=0.6))</pre><pre>    k = cv2.waitKey(1) &amp; 0xFF<br>    if k == 27:<br>        break<br>        <br>    # When c is pressed clear the canvas<br>    if k == ord(&#39;c&#39;):<br>        canvas = None</pre><pre>cv2.destroyAllWindows()<br>cap.release()</pre><p><strong>Note: Make sure the target maker color is not present in the background to avoid error. press c to clear the canvas.</strong></p><h3>Full Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da7dbb9eb3863361ba404a480911d91e/href">https://medium.com/media/da7dbb9eb3863361ba404a480911d91e/href</a></iframe><h3>Github link:</h3><p><a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/Virtual%20Pen">https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/Virtual%20Pen</a></p><p>other related projects</p><ul><li><a href="https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c">License Plate Recognition using OpenCV Python</a></li><li><a href="https://medium.com/programming-fever/invisibility-cloak-using-opencv-cf2d7d8894">Invisibility Cloak -using OpenCV</a></li><li><a href="https://medium.com/programming-fever/color-detection-using-opencv-python-6eec8dcde8c7">Color Detection using OpenCV Python</a></li></ul><h3>you can find me elsewhere on</h3><p>Instagram <a href="https://www.instagram.com/programming_fever/">@programming_fever</a></p><p>Facebook <a href="https://www.facebook.com/GeekyPRAVEE">@GeekyPRAVE</a></p><p>Twitter <a href="https://twitter.com/GeekyPRAVEE">@GeekyPRAVEE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d3a1d5902b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/programming-fever/draw-using-a-virtual-pen-on-a-computer-screen-using-opencv-in-python-71d3a1d5902b">Draw Using a Virtual Pen on a Computer Screen using OpenCV in Python</a> was originally published in <a href="https://medium.com/programming-fever">programming_fever</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to find HSV range of an Object for Computer Vision applications?]]></title>
            <link>https://medium.com/programming-fever/how-to-find-hsv-range-of-an-object-for-computer-vision-applications-254a8eb039fc?source=rss----7b66c578b334---4</link>
            <guid isPermaLink="false">https://medium.com/p/254a8eb039fc</guid>
            <dc:creator><![CDATA[Praveen]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 03:59:44 GMT</pubDate>
            <atom:updated>2020-07-28T04:24:18.904Z</atom:updated>
            <content:encoded><![CDATA[<p>HSV color space is more often used in computer vision owing to its superior performance compared to RGB color space in varying illumination levels. Often thresholding and masking is done in HSV color space. So it is very important to know the HSV values of the color which we want to filter out. HSV color space of OpenCV is a bit complicated than other software programmes like Gimp, Photoshop etc.So I have written a small python script to grab frames from a camera, print the HSV value and save(press ‘s’ ) our range array as a .npy file in our disk so we can access it later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IWFZSXmvICfrjlKF7mg_Q.png" /></figure><p>If a Computer Vision (CV) related application deals with detecting or tracking a specific object, then it is necessary to determine the range of HSV (Hue, Saturation, and Value) values of that object. This range is required to be specified as part of the coding to detect that object. If the correct range is not specified, the CV algorithm may pick-up noises as well, besides the actual object, leading to false detection and tracking.</p><p>In the below OpenCV code snippet, a sketch pen(pink colour) is about to be detected and tracked when it is moved in front of a webcam. To identify the sketch pen(pink colour)alone, not any other objects/ noises, it is necessary to specify a correct range of corresponding HSV numbers.</p><p>Refer to the Wikipedia <a href="https://en.wikipedia.org/wiki/HSL_and_HSV"><em>What is the HSV Color Model?</em> </a>to know more about HSV. Here is the quick look at what HSV is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_V7U0s6sTiMqAyIu8HuJg.png" /></figure><p><strong>HSV</strong> (<strong>hue, saturation, value</strong>) or <strong>HSB</strong> (<strong>hue, saturation, brightness</strong>) are alternative representations of the <a href="https://en.wikipedia.org/wiki/RGB_color_model">RGB color model</a>, designed in the 1970s by computer graphics researchers to more closely align with the way human vision perceives color-making attributes. In these models, colors of each <a href="https://en.wikipedia.org/wiki/Hue"><em>hue</em></a> are arranged in a radial slice, around a central axis of neutral colors which ranges from black at the bottom to white at the top.</p><p>The exact HSV range can be determined programmatically using OpenCV for an object to be identified or tracked. In the below video, a sketch pen(pink colour) which needs to be detected and tracked, is used to determine its HSV range.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUb2HeJtwb9E&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUb2HeJtwb9E&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f49d89afe7ca647a3459b1ac6bd8fc90/href">https://medium.com/media/f49d89afe7ca647a3459b1ac6bd8fc90/href</a></iframe><p>The Python script launches window as shown in the above video which shows sliders to adjust the HSV Min and Max range.Adjust the <em>Min</em> and <em>Max</em> slide bars in <em>Track bars</em> window till you get the desired object alone appear in <em>White</em> in <em>Thresh</em> window. Take the corresponding HSV range and use them in your code .We will also save(press ‘s’ ) our range array as a .npy file in our disk so we can access it later.</p><p>This below script will let you use track bars to adjust the hue, saturation, and value channels of the image. Adjust the track bars until only your target object is visible and the rest is black.</p><h3>Full Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26177418b14de0b33120a2b3ae127384/href">https://medium.com/media/26177418b14de0b33120a2b3ae127384/href</a></iframe><h3>other related projects</h3><ul><li><a href="https://medium.com/programming-fever/color-detection-using-opencv-python-6eec8dcde8c7">Color Detection using OpenCV Python</a></li><li><a href="https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c">License Plate Recognition using OpenCV Python</a></li><li><a href="https://medium.com/programming-fever/invisibility-cloak-using-opencv-cf2d7d8894">Invisibility Cloak -using OpenCV</a></li></ul><h3>you can find me elsewhere on</h3><p>Instagram <a href="https://www.instagram.com/programming_fever/">@programming_fever</a></p><p>Facebook <a href="https://www.facebook.com/GeekyPRAVEE">@GeekyPRAVE</a></p><p>Twitter <a href="https://twitter.com/GeekyPRAVEE">@GeekyPRAVEE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=254a8eb039fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/programming-fever/how-to-find-hsv-range-of-an-object-for-computer-vision-applications-254a8eb039fc">How to find HSV range of an Object for Computer Vision applications?</a> was originally published in <a href="https://medium.com/programming-fever">programming_fever</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Color Detection using OpenCV Python]]></title>
            <link>https://medium.com/programming-fever/color-detection-using-opencv-python-6eec8dcde8c7?source=rss----7b66c578b334---4</link>
            <guid isPermaLink="false">https://medium.com/p/6eec8dcde8c7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Praveen]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 06:43:46 GMT</pubDate>
            <atom:updated>2020-07-17T07:10:45.198Z</atom:updated>
            <content:encoded><![CDATA[<p>Color detection is necessary to recognize objects, it is also used as a tool in various image editing and drawing apps. I write a simple Python code to detect the color in the image using OpenCV and pandas (python libraries).</p><h3>What is Color Detection?</h3><p>Color detection is the process of detecting the name of any color. Simple isn’t it? Well, for humans this is an extremely easy task but for computers, it is not straightforward. Human eyes and brains work together to translate light into color. Light receptors that are present in our eyes transmit the signal to the brain. Our brain then recognizes the color.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcXdjXqn7GlE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcXdjXqn7GlE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcXdjXqn7GlE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44cf1b7563ffb431d4f323cfec14092/href">https://medium.com/media/d44cf1b7563ffb431d4f323cfec14092/href</a></iframe><h3>About the Python Project</h3><p>If you want to jump straight into the code without explanation then you can scroll down to the bottom of this page, where the complete code is provided or <a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/blob/master/LicensePlateRecoginition.ipynb">click here for GitHub link</a>.</p><p>In this color detection Python project, we are going to build an application through which you can automatically get the name of the color by clicking on them. So for this, we will have a data file that contains the color name and its values. Then we will calculate the distance from each color and find the shortest one.</p><h3>The Data set</h3><p>Colors are made up of 3 primary colors; red, green, and blue. In computers, we define each color value within a range of 0 to 255. So in how many ways we can define a color? The answer is 256*256*256 = 16,581,375. There are approximately 16.5 million different ways to represent a color. In our dataset, we need to map each color’s values with their corresponding names. But don’t worry, we don’t need to map all the values. We will be using a dataset that contains RGB values with their corresponding names.<a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/color%20detection">click here</a> to download csv file . csv file includes 865 color names along with their RGB and hex values.</p><h3>Steps for detecting color in an image</h3><p>Here are the steps to build an application in Python that can detect colors:</p><h3>1. Download and unzip the zip file</h3><p><a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/color%20detection">Color Detection Zip File</a></p><p>The project folder contains 3 files:</p><ul><li>Color detection.ipynb — main source code of our project.</li><li>color palette.jpg — sample image for experimenting.</li><li>Colors.csv — a file that contains our data set.</li></ul><h3>2. importing required package and load the image</h3><pre>import cv2<br>import numpy as np<br>import pandas as pd</pre><pre>img_path = “D://OpenCV//shape-detection//New folder//color palette.jpg”<br>img = cv2.imread(img_path)</pre><h3>3. Next, we read the CSV file with pandas</h3><p>The pandas library is very useful when we need to perform various operations on data files like CSV. pd.read_csv() reads the CSV file and loads it into the pandas DataFrame. We have assigned each column with a name for easy accessing.</p><pre>index=[“color”,”color_name”,”hex”,”R”,”G”,”B”]<br>csv = pd.read_csv(‘colors.csv’, names=index, header=None)</pre><h3>4. Set a mouse callback event on a window</h3><p>First, we created a window in which the input image will display. Then, we set a callback function which will be called when a mouse event happens.</p><pre>cv2.namedWindow(‘color detection’)<br>cv2.setMouseCallback(‘color detection’,draw_function)</pre><h3>5. Create the draw_function</h3><p>It will calculate the rgb values of the pixel which we double click. The function parameters have the event name, (x,y) coordinates of the mouse position, etc. In the function, we check if the event is double-clicked then we calculate and set the r,g,b values along with x,y positions of the mouse.</p><pre>def draw_function(event, x,y,flags,param):<br>    if event == cv2.EVENT_LBUTTONDBLCLK:<br>        global b,g,r,xpos,ypos, clicked<br>        clicked = True<br>        xpos = x<br>        ypos = y<br>        b,g,r = img[y,x]<br>        b = int(b)<br>        g = int(g)<br>        r = int(r)</pre><h3>6. Calculate distance to get color name</h3><p>We have the r,g and b values. Now, we need another function which will return us the color name from RGB values. To get the color name, we calculate a distance(d) which tells us how close we are to color and choose the one having minimum distance.</p><p>Our distance is calculated by this formula:</p><p><em>d = abs(Red — ithRedColor) + (Green — ithGreenColor) + (Blue — ithBlueColor)</em></p><pre>def getColorName(R,G,B):<br>    minimum = 10000<br>    for i in range(len(csv)):<br>        d = abs(R- int(csv.loc[i,&quot;R&quot;])) + abs(G-           int(csv.loc[i,&quot;G&quot;]))+ abs(B- int(csv.loc[i,&quot;B&quot;]))<br>        if(d&lt;=minimum):<br>            minimum = d<br>            cname = csv.loc[i,&quot;color_name&quot;]<br>    return cname</pre><h3>7. Display image on the window</h3><p>Whenever a double click event occurs, it will update the color name and RGB values on the window.</p><p>Using the cv2.imshow() function, we draw the image on the window. When the user double clicks the window, we draw a rectangle and get the color name to draw text on the window using cv2.rectangle and cv2.putText() functions.</p><pre>while(1):</pre><pre>cv2.imshow(&quot;color detection&quot;,img)<br>    if (clicked):<br>        cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1)</pre><pre>        text = getColorName(r,g,b)+&#39;R=&#39;+str(r)+&#39;G=&#39;+ str(g)          +&#39;B=&#39;+ str(b)<br>        cv2.putText(img, text,(50,50),2,0.8,                                       (255,255,255),2,cv2.LINE_AA)</pre><pre>        if(r+g+b&gt;=600):<br>            cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA)<br>            <br>        clicked=False</pre><pre>if cv2.waitKey(20) &amp; 0xFF ==27:<br>        break<br>cv2.destroyAllWindows()</pre><h3>Full Code</h3><p>&lt;script src=”<a href="https://gist.github.com/GeekyPRAVEE/fec689243de555827affc0c11a62fe86.js">https://gist.github.com/GeekyPRAVEE/fec689243de555827affc0c11a62fe86.js</a>&quot;&gt;&lt;/script&gt;</p><h3>output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*S4w84ppQkHCqCJknllEc5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*NjwJW9BeebYnUEX5iNh6MA.png" /></figure><p>Github Repo Link — <a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/color%20detection">https://github.com/GeekyPRAVEE/OpenCV-Projects/tree/master/color%20detection</a></p><h3>you can find me on</h3><p>Instagram <a href="https://www.instagram.com/programming_fever/">@programming_fever</a></p><p>Facebook <a href="https://www.facebook.com/GeekyPRAVEE">@GeekyPRAVE</a></p><p>Twitter <a href="https://twitter.com/GeekyPRAVEE">@GeekyPRAVEE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eec8dcde8c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/programming-fever/color-detection-using-opencv-python-6eec8dcde8c7">Color Detection using OpenCV Python</a> was originally published in <a href="https://medium.com/programming-fever">programming_fever</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[License Plate Recognition using OpenCV Python]]></title>
            <link>https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c?source=rss----7b66c578b334---4</link>
            <guid isPermaLink="false">https://medium.com/p/7611f85cdd6c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Praveen]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 18:55:33 GMT</pubDate>
            <atom:updated>2020-08-05T10:58:21.617Z</atom:updated>
            <content:encoded><![CDATA[<p>License Plate Recognition is an image-processing technology used to identify vehicles by their license plates. This technology is used in various security and traffic applications. I made this using simple Python code.</p><p><strong>Have a look at the final project in action:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUGOCGT9MPZA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUGOCGT9MPZA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUGOCGT9MPZA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb1eb9258925ec9b5ece6c0ca65bb00/href">https://medium.com/media/3fb1eb9258925ec9b5ece6c0ca65bb00/href</a></iframe><h3>Steps involved in License Plate Recognition</h3><p><strong>1. License Plate Detection:</strong> The first step is to detect the License plate from the car. We will use the contour option in OpenCV to detect for rectangular objects to find the number plate. The accuracy can be improved if we know the exact size, color and approximate location of the number plate. Normally the detection algorithm is trained based on the position of camera and type of number plate used in that particular country. This gets trickier if the image does not even have a car, in this case we will an additional step to detect the car and then the license plate.</p><p><strong>2. Character Segmentation:</strong> Once we have detected the License Plate we have to crop it out and save it as a new image. Again this can be done easily using OpenCV.</p><p><strong>3.</strong> <strong>Character Recognition:</strong> Now, the new image that we obtained in the previous step is sure to have some characters (Numbers/Alphabets) written on it. So, we can perform OCR (Optical Character Recognition) on it to detect the number</p><h3>1. License Plate Detection</h3><p>Let’s take a sample image of a car and start with detecting the License Plate on that car. We will then use the same image for Character Segmentation and Character Recognition as well. If you want to jump straight into the code without explanation then you can scroll down to the bottom of this page, where the complete code is provided or <a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/blob/master/LicensePlateRecoginition.ipynb">click here for GitHub link</a>. The test image that I am using for this tutorial is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOecD-Ww8mJA_rK0ivsPQg.jpeg" /><figcaption>image source link: <a href="https://rb.gy/lxmiuv">https://rb.gy/lxmiuv</a></figcaption></figure><p><strong>Step 1:</strong> <strong>Resize the image to the required size and then grayscale it</strong>. The code for the same is given below</p><pre><strong>img = cv2.resize(img, (620,480) )</strong><br><strong>gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #convert to grey scale</strong></pre><p>Resizing we help us to avoid any problems with bigger resolution images, make sure the number plate still remains in the frame after resizing. Gray scaling is common in all image processing steps. This speeds up other following process sine we no longer have to deal with the color details when processing an image. The image would be transformed something like this when this step is done</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WCSzHL66WGYexk5LFOdAZw.png" /></figure><p><strong>Step 2: </strong>Every image will have useful and useless information, in this case for us only the license plate is the useful information the rest are pretty much useless for our program. This useless information is called noise. Normally <strong>using a bilateral filter (Blurring) will remove the unwanted details from an image</strong>. The code for the same is blurred</p><pre><strong>gray = cv2.bilateralFilter(gray, 13, 15, 15)</strong></pre><p>Syntax is <em>destination_image = cv2.bilateralFilter(source_image, diameter of pixel, sigmaColor, sigmaSpace).</em> You can increase the sigma color and sigma space from 15 to higher values to blur out more background information, but be careful that the useful part does not get blurred. The output image is shown below, as you can see the background details (tree and building) are blurred in this image. This way we can avoid the program from concentrating on these regions later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*v8M3mFn8fN-wGpYopP7SgA.png" /></figure><p><strong>Step 3:</strong> The next step is interesting where we perform <strong>edge detection</strong>. There are many ways to do it, the most easy and popular way is to use the <strong>canny edge method from OpenCV.</strong> The line to do the same is shown below</p><pre><strong>edged = cv2.Canny(gray, 30, 200) #Perform Edge detection</strong></pre><p>The syntax will be <em>destination_image = cv2.Canny(source_image, thresholdValue 1, thresholdValue 2).</em> The Threshold Vale 1 and Threshold Value 2 are the minimum and maximum threshold values. Only the edges that have an intensity gradient more than the minimum threshold value and less than the maximum threshold value will be displayed. The resulting image is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*V-AVcud7oEawDIVwc-TIsw.png" /></figure><p><strong>Step 4: </strong>Now we can start <strong>looking for contours on our image</strong></p><pre><strong>contours=cv2.findContours(edged.copy(),cv2.RETR_TREE,<br>                                            cv2.CHAIN_APPROX_SIMPLE)</strong><br><strong>contours = imutils.grab_contours(contours)</strong><br><strong>contours = sorted(contours,key=cv2.contourArea, reverse = True)[:10]</strong><br><strong>screenCnt = None</strong></pre><p><strong>Once the counters have been detected we sort them from big to small</strong> and consider only the first 10 results ignoring the others. In our image the counter could be anything that has a closed surface but of all the obtained results the license plate number will also be there since it is also a closed surface.</p><p>To filter the license plate image among the obtained results, we will loop though all the results and check which has a rectangle shape contour with four sides and closed figure. Since a license plate would definitely be a rectangle four sided figure.</p><pre><strong>for c in cnts:</strong><br>    <strong># approximate the contour</strong><br>    <strong>peri = cv2.arcLength(c, True)</strong><br>    <strong>approx = cv2.approxPolyDP(c, 0.018 * peri, True)</strong><br>    <strong># if our approximated contour has four points, then</strong><br>    <strong># we can assume that we have found our screen</strong><br>    <strong>if len(approx) == 4:</strong><br>        <strong>screenCnt = approx</strong><br>        <strong>break</strong></pre><p>Once we have found the right counter we save it in a variable called <em>screenCnt </em>and then draw a rectangle box around it to make sure we have detected the license plate correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*qTGnpZiV3RM-jfAo8jS9Jw.png" /></figure><p><strong>Step 5: </strong>Now that we know where the number plate is, the remaining information is pretty much useless for us. So we can <strong>proceed with masking the entire picture except for the place where the number plate is.</strong> The code to do the same is shown below</p><pre><strong># Masking the part other than the number plate</strong><br><strong>mask = np.zeros(gray.shape,np.uint8)</strong><br><strong>new_image = cv2.drawContours(mask,[screenCnt],0,255,-1,)</strong><br><strong>new_image = cv2.bitwise_and(img,img,mask=mask)</strong></pre><p>The masked new image will appear something like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ev_QJJh-PV4OU2uu0myJpQ.png" /></figure><h3>2. Character Segmentation</h3><p>The next step in <strong>Number Plate Recognition</strong> is to segment the license plate out of the image by <strong>cropping it and saving it as a new image. </strong>We can then use this image to detect the character in it. The code to crop the roi (Region of interest) image form the main image is shown below</p><pre><strong># Now crop</strong><br><strong>(x, y) = np.where(mask == 255)</strong><br><strong>(topx, topy) = (np.min(x), np.min(y))</strong><br><strong>(bottomx, bottomy) = (np.max(x), np.max(y))</strong><br><strong>Cropped = gray[topx:bottomx+1, topy:bottomy+1]</strong></pre><p>The resulting image is shown below. Normally added to cropping the image, we can also gray it and edge it if required. This is done to improve the character recognition in next step. However I found that it works fine even with the original image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*S74vkxSktEnCTGgfynwEWw.png" /></figure><h3>3. Character Recognition</h3><p>The Final step in this <strong>Number Plate Recognition</strong> is to actually <strong>read the number plate information from the segmented image</strong>. We will use the<strong><em> pytesseract</em></strong> package to read characters from image, just like we did in previous tutorial. The code for the same is given below</p><pre><strong>#Read the number plate</strong><br><strong>text = pytesseract.image_to_string(Cropped, config=&#39;--psm 11&#39;)</strong><br><strong>print(&quot;</strong>Detected license plate Number is:<strong>&quot;,text)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*zgibVNFlXvy0zYepG2CVwQ.png" /></figure><p>As you can see the original image had the number “CZ20FSE” on it and our program has detected it printed the same value on jupyter notebook.</p><h3>Fail Cases in Number Plate Recognition</h3><p>The complete code of this <strong>License Plate Recognition</strong> can be downloaded from <a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/blob/master/LicensePlateRecoginition.ipynb">here</a>, it contains the program and the test images that we used to check our program. Without being said, it is to be remembered that the results from this method will not be accurate<strong>. The accuracy depends on the clarity of image, orientation, light exposure etc</strong>. To get better results you can try implementing Machine learning algorithms along with this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*26hgGTuJJBbt87yUDQTZDQ.png" /></figure><p>As you can see, our program was able to detect the license plate correctly and crop it. But the<em> Tesseract</em> library has failed to recognize the characters properly. Instead of the actual “MH 13 CD 0096” the OCR has recognized it to be “MH13CD 0036”. <strong>Problems like this can be corrected by either using better orientation images or by configuring the <em>Tesseract</em> engine</strong>.</p><h3>Other Successful Examples</h3><p>Most of the times of the image quality and orientation is correct, the program was able to identify the license plate and read the number from it. The below snap shots show the successful results obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*zFTef8dEtc-e1CyX223adw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*dslRXGbz_pTq7J9mDV6aJA.png" /></figure><h3>Full code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c313d43a835acdff5845f1a70dc6e829/href">https://medium.com/media/c313d43a835acdff5845f1a70dc6e829/href</a></iframe><p>Github Repo Link — <a href="https://github.com/GeekyPRAVEE/OpenCV-Projects/blob/master/LicensePlateRecoginition.ipynb">https://github.com/GeekyPRAVEE/OpenCV-Projects/blob/master/LicensePlateRecoginition.ipynb</a></p><h3>you can find me at</h3><p>Instagram <a href="https://www.instagram.com/programming_fever/">@programming_fever</a></p><p>Facebook <a href="https://www.facebook.com/GeekyPRAVEE">@GeekyPRAVE</a></p><p>Twitter <a href="https://twitter.com/GeekyPRAVEE">@GeekyPRAVEE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7611f85cdd6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c">License Plate Recognition using OpenCV Python</a> was originally published in <a href="https://medium.com/programming-fever">programming_fever</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invisibility Cloak -using OpenCV]]></title>
            <link>https://medium.com/programming-fever/invisibility-cloak-using-opencv-cf2d7d8894?source=rss----7b66c578b334---4</link>
            <guid isPermaLink="false">https://medium.com/p/cf2d7d8894</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[opencv-project]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Praveen]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 07:03:12 GMT</pubDate>
            <atom:updated>2020-08-05T11:54:44.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>Harry Potter’s Invisibility Cloak using OpenCV Python</h3><p>If you are a Harry Potter fan , you would know what an Invisibility Cloak is. Yes! It’s the cloak that makes Harry Potter invisible. We will make this happen with few line of python code in OpenCV.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*xIho0iQQPs5SyrCHvw55SA.gif" /><figcaption>harry potter’s invisibility cloak</figcaption></figure><h3>How it works</h3><p>This technique is opposite to the <strong>Green Screening</strong>. In green screening, we remove background but here we will remove the foreground frame.</p><ol><li>Capture and store the background frame</li><li>Detect the defined color using color detection and segmentation algorithm.</li><li>Segment out the defined colored part by generating a mask.</li><li>Generate the final augmented output to create a magical effect. [ output.avi ]</li></ol><h3>Let’s Start</h3><h3>You need the following libraries</h3><pre>import cv2<br>import time<br>import numpy as np</pre><p>You will need to update the HSV value of the colour you choose accordingly in the code. Like if you have red cloth or blue cloth that you want to make invisible than you will need to set value accordingly.</p><p>Well, <strong>“What is HSV?”</strong></p><h3>Hue Saturation Value</h3><h3>H : Hue</h3><p>Hue is the colour portion of the model, expressed as a number from 0 to 360 degrees:</p><ul><li><strong>Red</strong> falls between 0 and 60 degrees.</li><li><strong>Yellow</strong> falls between 61 and 120 degrees.</li><li><strong>Green</strong> falls between 121–180 degrees.</li><li><strong>Cyan</strong> falls between 181–240 degrees.</li><li><strong>Blue</strong> falls between 241–300 degrees.</li><li><strong>Magenta</strong> falls between 301–360 degrees.</li></ul><h3>S : Saturation</h3><p>Saturation describes the amount of grey in a particular colour, from 0 to 100 percent. Reducing this component toward zero introduces more grey and produces a faded effect. Sometimes, saturation appears as a range from just 0–1, where 0 is grey, and 1 is a primary colour.</p><h3>V : Value (Brightness)</h3><p>Value works in conjunction with saturation and describes the brightness or intensity of the colour, from 0–100 percent, where 0 is completely black, and 100 is the brightest and reveals the most colour.</p><p><strong>Recording and caching the background for each frame.</strong></p><p>We are replacing the red colored pixels with the background pixels to create the invisible effect in the video. For doing this, we have to store the background image for each frame.</p><pre>##reading from the webcam<br>cap = cv2.VideoCapture(0)## Allow the system to sleep for 3 seconds before the webcam starts<br>time.sleep(3)<br>count = 0<br>background = 0## Capture the background in range of 60<br>for i in range(60):<br>    ret, background = cap.read()<br>background = np.flip(background, axis=1)<br></pre><p><strong>Detecting the define color portion In each frame</strong></p><p>In this step, we will put our focus on detecting the red part in the image. We will convert the RGB (red-blue-green) to HSV(hue-saturation-value) because RGB values are highly sensitive to illumination. After the conversion of RGB to HSV, it is time to specify the range of color to detect red color in the video. Below color values are for red color</p><pre>## Read every frame from the webcam, until the camera is open<br>while (cap.isOpened()):<br>    ret, img = cap.read()<br>    if not ret:<br>        break<br>    count += 1<br>    img = np.flip(img, axis=1)    ## Convert the color space from BGR to HSV<br>    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)    ## Generat masks to detect red color<br>    lower_red = np.array([0, 125, 50])<br>    upper_red = np.array([10, 255,255])<br>    mask1 = cv2.inRange(hsv, lower_red, upper_red)    lower_red = np.array([170, 120, 70])<br>    upper_red = np.array([180, 255, 255])<br>    mask2 = cv2.inRange(hsv, lower_red, upper_red)    mask1 = mask1 + mask2</pre><p><strong>Replacing the red portion with a mask image in each frame</strong></p><p>Now, we have a red part of the video in the ‘mask’ image, we will segment the mask part from the frames. We will do a morphology open and dilation for that.</p><pre>## Open and Dilate the mask image<br>mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))<br>mask1 = cv2.morphologyEx(mask1, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8))## Create an inverted mask to segment out the red color from the frame<br>mask2 = cv2.bitwise_not(mask1)## Segment the red color part out of the frame using bitwise and with the inverted mask<br>res1 = cv2.bitwise_and(img, img, mask=mask2)## Create image showing static background frame pixels only for the masked region<br>res2 = cv2.bitwise_and(background, background, mask=mask1)</pre><h3>Full Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b0e98a556f69ce9d7b61de0488f4ae/href">https://medium.com/media/69b0e98a556f69ce9d7b61de0488f4ae/href</a></iframe><p>Github Repo Link —<a href="https://github.com/PROpraveee/OpenCV-Projects/blob/master/invisible%20cloak.ipynb">https://github.com/PROpraveee/OpenCV-Projects/blob/master/invisible%20cloak.ipynb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*AzgVLRo_mghjYX4jA6_ZIQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2d7d8894" width="1" height="1" alt=""><hr><p><a href="https://medium.com/programming-fever/invisibility-cloak-using-opencv-cf2d7d8894">Invisibility Cloak -using OpenCV</a> was originally published in <a href="https://medium.com/programming-fever">programming_fever</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>