<?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[Stories by Sowmiya Narayanan Govindaraj on Medium]]></title>
        <description><![CDATA[Stories by Sowmiya Narayanan Govindaraj on Medium]]></description>
        <link>https://medium.com/@gsnWrites?source=rss-150dc71378ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s3y_4js2evManktX3gqm_g.jpeg</url>
            <title>Stories by Sowmiya Narayanan Govindaraj on Medium</title>
            <link>https://medium.com/@gsnWrites?source=rss-150dc71378ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:02:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gsnWrites/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is Perspective Warping ? | OpenCV and Python]]></title>
            <link>https://pub.towardsai.net/what-is-perspective-warping-opencv-and-python-750e7a13d386?source=rss-150dc71378ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/750e7a13d386</guid>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sowmiya Narayanan Govindaraj]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 19:20:14 GMT</pubDate>
            <atom:updated>2020-09-27T02:35:45.183Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/computer-vision">Computer Vision</a></h4><h3>What is Perspective Warping? | OpenCV and Python</h3><h4>A step-by-step guide to applying a perspective transformation on images</h4><p>Computer vision is all abuzz now. People everywhere are working on some form of deep-learning-based computer vision projects. But before the advent of Deep Learning, image processing techniques were employed to manipulate and transform images in order to obtain insights that would help us achieve the task at hand. Today, let’s see how we can implement a simple yet helpful technique known as Perspective Projection to warp an image.</p><p>But wait! What does warping an image mean? I could explain it with a lot of fancy words and technical jargon. But then, it will be easy to just show the end results so that you can learn by seeing. You are reading a Computer Vision article anyway :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAz3hmjnG03rnD9MacYGng.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AE_faab3HWeif7aPgbeq6g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBC37s6C0e4XFgy4tvvv_w.jpeg" /><figcaption>Base Image (<a href="https://unsplash.com/photos/Dnkr_lmdKi8">Source</a>) — Subject Image (<a href="https://unsplash.com/photos/demvKRNvtLY">Source</a>) — Warped Output (Image by Author)</figcaption></figure><p>So basically, you take an image and shear it to make it fit into a canvas of any desired shape. Note that the other way round is also possible. Now that, that’s out of the way, let’s take a look at how we can implement this using OpenCV and our trustworthy friend — Python(❤).</p><p>For you people who just want the code, no worries, I got you guys covered :P Here is the link to my GitHub <a href="https://github.com/GSNCodes/Image_Overlaying_Using_Perspective_Transform">repository</a>.</p><p>Before we get into the main parts of the code, we must first import the necessary libraries.</p><pre>import cv2<br>import numpy as np</pre><p>Now, let’s read in the base image and the subject image as follows.</p><pre>base_image = cv2.imread(&#39;base_img.jpg&#39;)<br>base_image_copy = base_image.copy()<br>subject_image = cv2.imread(&#39;subject.jpg&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAz3hmjnG03rnD9MacYGng.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AE_faab3HWeif7aPgbeq6g.jpeg" /><figcaption><a href="https://unsplash.com/photos/Dnkr_lmdKi8">Base Image</a>(left) — <a href="https://unsplash.com/photos/demvKRNvtLY">Subject Image</a>(right)</figcaption></figure><p>Initialize an array to store the coordinates of the 4 corners within which we want to overlay our subject image. We can choose these 4 points manually using the <strong>setMouseCallback()</strong> function as shown down below.</p><pre>def click_event(event, x, y, flags, params):<br>    if event == cv2.EVENT_LBUTTONDOWN:<br>        cv2.circle(base_image_copy, (x, y), 4, (0, 0, 255), -1)<br>        points.append([x, y])<br>        if len(points) &lt;= 4:<br>            cv2.imshow(&#39;image&#39;, base_image_copy)</pre><pre>points = []</pre><pre>base_image = cv2.imread(&#39;base_img.jpg&#39;)<br>base_image_copy = base_image.copy()<br>subject_image = cv2.imread(&#39;subject.jpg&#39;)<br><br>cv2.imshow(&#39;image&#39;, base_image_copy)<br>cv2.setMouseCallback(&#39;image&#39;, click_event)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p>In the code snippet given above, we define a function called <strong>click_event() </strong>and pass it as an argument to the <strong>setMouseCallback()</strong> function. With this method, we’ll first display the base image. We can then manually choose four points within the image to set as our target. Our subject image would be warped onto this target. The coordinates are recorded when the left mouse button is pressed. These are stored in the points array we initialized earlier. The selected points are highlighted as red dots, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbJGW6mAyYllQ_LafavKZw.gif" /><figcaption>Selecting Corner Points (GIF by Author)</figcaption></figure><p>As we know, each one of us might choose 4 points in any random order. There is hence a need to maintain a constant ordering among the chosen points. I chose to order the points in a clockwise manner, i.e, from top-left to top-right to bottom-right to bottom-left. This is achieved by the <strong>sort_pts() </strong>method shown below. We use the fact that the sum of the x- and y-coordinates are minimum at the top-left corner and maximum at the bottom-right corner. Similarly, the difference between them is minimum at the top-right corner and maximum at the bottom-left corner. Take a moment to verify that it’s true by yourself. <strong>Keep in mind that for images, the origin is at the top-left corner of the image.</strong></p><pre>def sort_pts(points):<br>    sorted_pts = np.zeros((4, 2), dtype=&quot;float32&quot;)<br>    s = np.sum(points, axis=1)<br>    sorted_pts[0] = points[np.argmin(s)]<br>    sorted_pts[2] = points[np.argmax(s)]<br><br>    diff = np.diff(points, axis=1)<br>    sorted_pts[1] = points[np.argmin(diff)]<br>    sorted_pts[3] = points[np.argmax(diff)]<br><br>    return sorted_pts</pre><pre>sorted_pts = sort_pts(points)</pre><p>After sorting the points, let&#39;s use them to calculate the transformation matrix. We create a numpy array called “<strong>pts1</strong>” which holds the coordinates of the 4 corners of the subject image. Similarly, we create a list called “<strong>pts2</strong>” which holds the sorted points. The order of the coordinates of “<strong>pts1</strong>” should match that of “<strong>pts2</strong>”.</p><pre>h_base, w_base, c_base = base_image.shape<br>h_subject, w_subject = subject_image.shape[:2]<br><br>pts1 = np.float32([[0, 0], [w_subject, 0], [w_subject, h_subject],                     [0, h_subject]])</pre><pre>pts2 = np.float32(sorted_pts)</pre><p>We now obtain the transformation matrix that is required to warp the subject image. This is obtained using the function, <strong>cv2.getPerspectiveTransform()</strong>. Since we want to transform the subject image in such a way that it fits the box we chose in the base image, the “<strong>src</strong>” should be “<strong>pts1 </strong>”and the “<strong>dst</strong>” should be “<strong>pts2</strong>”. The size of the generated image can be specified as a tuple. We make sure the resultant image has the dimensions of the base image. Using the generated matrix we can warp the image using <strong>cv2.warpPerspective() </strong>method as shown in the given snippet.</p><pre>transformation_matrix = cv2.getPerspectiveTransform(pts1, pts2)<br><br>warped_img = cv2.warpPerspective(subject_image, transformation_matrix, (w_base, h_base))</pre><pre>cv2.imshow(&#39;Warped Image&#39;, warped_img)</pre><p>The warped image would look like this:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkuLxHnJ7ICFcQCKkNZ80w.png" /><figcaption>Warped Image (Image by Author)</figcaption></figure><p>The next step is to create a mask for which we create a blank image with the shape of the base image.</p><pre>mask = np.zeros(base_image.shape, dtype=np.uint8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*SnD4LJn16QdfLGPh3IiRIQ.png" /><figcaption>Initial Mask (Image by Author)</figcaption></figure><p>Onto this blank mask we draw a polygon with corners given by the “<strong>sorted_pts</strong>” and fill it with white color using the <strong>cv2.fillConvexPoly() </strong>method. The resultant mask would look like this.</p><pre>roi_corners = np.int32(sorted_pts)<br><br>cv2.fillConvexPoly(mask, roi_corners, (255, 255, 255))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSt04jsVgfJSwJogwvULhA.png" /><figcaption>Filled-In Mask (Image by Author)</figcaption></figure><p>Now we invert the mask colors using the <strong>cv2.bitwise_not() </strong>method.</p><pre>mask = cv2.bitwise_not(mask)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJV-0wj8IWQ94Rnog7Q7Ow.png" /><figcaption>Inverted Mask (Image by Author)</figcaption></figure><p>Now we take the mask and base image and perform bitwise-AND operation using the <strong>cv2.bitwise_and() </strong>method.</p><pre>masked_image = cv2.bitwise_and(base_image, mask)</pre><p>This would give us an image as shown below. You can see that the area onto which the subject image is to be placed alone, is black.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2MFGMqsE5lrvLgklHBipA.png" /><figcaption>Masked Base Image (Image by Author)</figcaption></figure><p>The final step would be to take the warped image and the masked image and perform bitwise-OR operation using the <strong>cv2.bitwise_or() </strong>method. This would generate the fused image we set out to accomplish.</p><pre>output = cv2.bitwise_or(warped_img, masked_image)<br>cv2.imshow(&#39;Fused Image&#39;, output)<br>cv2.imwrite(&#39;Final_Output.png&#39;, output)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><p>We have done it! We have successfully overlaid one image onto another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBC37s6C0e4XFgy4tvvv_w.jpeg" /><figcaption>Fused Image (Image by Author)</figcaption></figure><p>This is a very simple use case of perspective transformation. You can use this for generating a bird’s eye view of an area when you are tracking the movement of objects/persons in the frame. The only limit is your imagination.</p><p>The entire code for this article could be found in my GitHub repository through this <a href="https://github.com/GSNCodes/Image_Overlaying_Using_Perspective_Transform">link</a>.</p><p><em>~~</em> <em>SowmiyaNarayanan G</em></p><p><strong>PS:-</strong></p><p>Feel free to reach out to me if you have any doubts, I am happy to help. My doors are always open to constructive criticism, and hence don’t hesitate to let me know what you think of my work. You can also connect with me on <a href="https://www.linkedin.com/in/sowmiyanarayanan-g/">LinkedIn</a>.</p><p><strong>Mind Bytes:-</strong></p><p><em>“Everything you can imagine is real”</em>― Pablo Picasso</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750e7a13d386" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/what-is-perspective-warping-opencv-and-python-750e7a13d386">What is Perspective Warping ? | OpenCV and Python</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Segmentation Using Mask  R-CNN]]></title>
            <link>https://medium.com/data-science/image-segmentation-using-mask-r-cnn-8067560ed773?source=rss-150dc71378ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/8067560ed773</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sowmiya Narayanan Govindaraj]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 16:14:44 GMT</pubDate>
            <atom:updated>2020-07-12T16:14:44.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Segmentation Using Mask R-CNN</h3><h4>A simple tutorial to perform instance segmentation using Python and OpenCV</h4><p>Computer Vision as a field of research has seen a lot of development in recent years. Ever since the introduction of Convolutional Neural Networks, the state of the art in domains such as classification, object detection, image segmentation, etc. have constantly been challenged. With the aid of sophisticated hardware providing very high computational power, these neural network models are being employed in real-time in emerging fields such as Autonomous Navigation.</p><p>Our topic of focus today will be a sub-field of Computer Vision known as Image Segmentation. To be more precise, we’ll be performing Instance Segmentation on an image or video. Okay, that was a lot of technical jargon. Let’s reel it back a bit and understand what those terms mean. Each of these would require a post in itself and we won’t dive too deep into it now. I might write some articles on each of them separately in the near future. For now, let’s understand what Image Segmentation is, in a simplified manner. Also, if you do not know what Object Detection is, I suggest you read up on it as it would make it easier to understand the upcoming concepts easily. I have also written a concise article on implementing an Object Detection algorithm. Should you be interested in it, you can find it in my profile.</p><h4><strong>What is Image Segmentation?</strong></h4><p>Image segmentation is the process of classifying each pixel in the image as belonging to a specific category. Though there are several types of image segmentation methods, the two types of segmentation that are predominant when it comes to the domain of Deep Learning are:</p><ul><li>Semantic Segmentation</li><li>Instance Segmentation</li></ul><p>Let me draw a concise comparison between the two. In Semantic Segmentation every pixel of an object belonging to a particular class is given the same label/color value. On the other hand, in Instance Segmentation every pixel of each object of a class is given a separate label/color value. Take a look at the image below and read the previous sentence once again to understand it clearly. I hope it makes sense now :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbZwyyK1EUvXoOrmfE2wtQ.png" /><figcaption>Source — <a href="https://engineering.matterport.com/splash-of-color-instance-segmentation-with-mask-r-cnn-and-tensorflow-7c761e238b46">Matterport</a></figcaption></figure><h4>Implementation!</h4><p>Mask R-CNN (Regional Convolutional Neural Network) is an Instance segmentation model. In this tutorial, we’ll see how to implement this in python with the help of the OpenCV library. If you are interested in learning more about the inner-workings of this model, I’ve given a few links at the reference section down below. That would help you understand the functionality of these models in great detail.</p><p>We begin by cloning (or downloading ) the given repository:-</p><p><a href="https://github.com/matterport/Mask_RCNN">GitHub - matterport/Mask_RCNN: Mask R-CNN for object detection and instance segmentation on Keras and TensorFlow</a></p><p>Make sure you have all the dependencies listed in the <strong>requirements.txt</strong> installed in your python environment. After which, don’t forget to run the command <strong>python setup.py install</strong>. We’ll be using a model pre-trained on the coco dataset. The weights for which can be downloaded from <a href="https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5">here</a> and the class names could be obtained from the <strong>coco_classes.txt</strong> file from my <a href="https://github.com/GSNCodes/Instance_Segmentation_Mask_RCNN">repository</a>. Now let’s start by creating a file called <strong>mask.py</strong> within the cloned or downloaded repository and import the required libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c342dded127391e8a503f3af030384b5/href">https://medium.com/media/c342dded127391e8a503f3af030384b5/href</a></iframe><p>We will be using our own custom class and hence will be inheriting the existing <strong>CocoConfig</strong> class and overriding the values of its variables. Note that you can set these values according to the capability of your GPU.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c7476b0ebe10c96642c6e7da8073bc/href">https://medium.com/media/71c7476b0ebe10c96642c6e7da8073bc/href</a></iframe><p>Now we’ll create a function called <strong>prepare_mrcnn_model()</strong> that takes care of reading the class labels as well as initializing the model object according to our custom config. We also specify a color-to-object mapping to implement semantic segmentation too(if required). We’ll talk about this in a bit. The mode of our model should be set to ‘inference’ as we are going to use it for testing directly. The path to the pre-trained weights is supplied so that it can be loaded into the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a535965fe85dfb997017e6df42f0f9d3/href">https://medium.com/media/a535965fe85dfb997017e6df42f0f9d3/href</a></iframe><p>The next function will be the most crucial part of this tutorial. Don’t be scared by its length, it’s the most simple one yet! We will now pass the test image to the detect function of our model object. This would perform all the detection and segmentation of objects for us. We now have two options — we can either choose to assign every object of the class the same color or assign every object irrespective of its class a distinct color. Since this post is steadfast about implementing instance segmentation, I chose the latter. I have given you the flexibility to do both so that you can strengthen your understanding of the same. This can be done by toggling the instance_segmentation parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0c0cb175f7e01f1573fc8e63e94a890/href">https://medium.com/media/c0c0cb175f7e01f1573fc8e63e94a890/href</a></iframe><p>The code above sketches the bounding box of the object while also segmenting it at the pixel level. It also provides the class that object belongs to along with the score. I’ve also given you the option to visualize the output using the internal visualization function present in Matterport’s MRCNN implementation. This can be accessed using the mrcnn_visualize boolean parameter shown above.</p><p>Now that we have our model and the code to process the output which it produces, we only need to read and pass in the input image. This is done by the perform_inference_image() function given down below. The save_enable parameter allows us to save the processed image with the objects segmented.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/701f3101e595880a4fa84d4a206f628a/href">https://medium.com/media/701f3101e595880a4fa84d4a206f628a/href</a></iframe><p>This can now also be easily extended to video and live web-cam feed as shown by the perform_inference_video() function here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/118ae292356845fbd844bae382609c9f/href">https://medium.com/media/118ae292356845fbd844bae382609c9f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LaO5yfIYt1xo6fxr_1FIng.png" /><figcaption>Base Image Source — <a href="https://cocodataset.org/#explore?id=444207">MS COCO Dataset</a></figcaption></figure><p>As you can see in the image above, every object is segmented. The model detects multiple instances of the class book and hence assigns each instance a separate color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*X4Av2ZpweXu_Rbg5ecVakg.png" /><figcaption>Here is another example where the objects are segmented. Base image source : <a href="https://cocodataset.org/#explore?id=377983">MS COCO D</a>ataset</figcaption></figure><p>That is it guys! You now have a working instance segmentation pipeline for you to put to use. The entire code for this project as well as a clean and easy to use interface can be found in my repository given <a href="https://github.com/GSNCodes/Instance_Segmentation_Mask_RCNN">here</a>. Additional steps to use the same can also be found there. I do realize that some of you might not have a CUDA compatible GPU or rather no GPU at all. So, I have also provided a Colab notebook that can be used to run the code. Integrating web-cam usage in Colab still eludes me and hence inference can only be done on images and video files for now. <strong>Matterport’s Mask R-CNN code supports Tensorflow 1.x by default. If you are using TF2.x, you are better off forking/cloning my repository directly as I have ported the code to support TF2.x.</strong></p><p>I suggest that you read up on the R-CNN architectures (especially Faster R-CNN) to completely understand the working of Mask R-CNN. I’ve given links to some good resources in the references section down below. Also, having a sound understanding of how Object Detection works would make it easy to comprehend the crux of Image Segmentation.</p><p><em>~~</em> <em>SowmiyaNarayanan G</em></p><p><strong>Mind Bytes:-</strong></p><p><em>“The secret of getting ahead is getting started.” </em>— Mark Twain.</p><h4>PS:-</h4><p>Feel free to reach out to me if you have any doubts, I am here to help. I am open to any sorts of criticism to improve my work so that I can better cater to the needs of explorers such as yourself in the future. Don’t hesitate to reach out to let me know what you think. You can also connect with me on <a href="https://www.linkedin.com/in/sowmiyanarayanan-g/">LinkedIn</a>.</p><h4>References:-</h4><ul><li>The original ‘Mask R-CNN’ paper — <a href="https://arxiv.org/pdf/1703.06870.pdf">https://arxiv.org/pdf/1703.06870.pdf</a></li><li>Matterport’s Mask R-CNN <a href="https://github.com/matterport/Mask_RCNN">Repository</a> &lt;— “ Super Important 😃”</li><li><a href="https://towardsdatascience.com/r-cnn-fast-r-cnn-faster-r-cnn-yolo-object-detection-algorithms-36d53571365e">R-CNN, Fast R-CNN, Faster R-CNN, YOLO — Object Detection Algorithms</a></li><li>The code to my <a href="https://github.com/GSNCodes/YOLOv3_Object_Detection_OpenCV">YOLOv3 implementation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8067560ed773" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-segmentation-using-mask-r-cnn-8067560ed773">Image Segmentation Using Mask  R-CNN</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diagnosing Pneumonia with Deep Learning]]></title>
            <link>https://medium.com/swlh/diagnosing-pneumonia-with-deep-learning-709e6d3b38c2?source=rss-150dc71378ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/709e6d3b38c2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Sowmiya Narayanan Govindaraj]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 18:32:11 GMT</pubDate>
            <atom:updated>2020-07-03T08:27:28.418Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using PyTorch and CNNs to classify x-ray images that show traits of Pneumonia.</h4><p>Utilizing computer vision and deep learning for diagnosing medical conditions is an extensive area of research and there have been several breakthroughs in this field. Classifying images based on some criteria into various categories is termed Image Classification. In this article, I’ll be explaining the concept of Binary Classification, a sub-set of Image Classification. We’ll develop a deep learning model using PyTorch and achieve good enough results with the use of a concept called Transfer Learning. The model would analyze and classify x-ray images into two categories — “Pneumonia” and “Normal”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*3IHJWGT-KXDebz9YkVb_Eg.png" /><figcaption>Example Output — Image by Author</figcaption></figure><p>Let’s now take a stroll through the pipeline:-</p><p>As always, the first step would be to import the necessary libraries and packages. My framework of choice for this venture is PyTorch. The libraries are imported as shown down below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2faf17d684981245e0a08ef3c57dbf95/href">https://medium.com/media/2faf17d684981245e0a08ef3c57dbf95/href</a></iframe><p>The dataset we’ll be using is called “Chest X-Ray Images (Pneumonia)” by Paul Mooney and can be found on Kaggle using this <a href="https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia">link</a>. The dataset is organized into 3 folders (train, test, val) and contains sub-folders for each image category (Pneumonia/Normal). There are 5,863 X-Ray images (JPEG) in total. It’s around 1-GB, but you can use the notebook environment built into Kaggle if you do not want to download the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5669f293d8891675e94deb4eb03858e/href">https://medium.com/media/c5669f293d8891675e94deb4eb03858e/href</a></iframe><p>Using the code above we can find that there are 3875 x-ray images showing traits of Pneumonia and 1341 x-ray images that are normal. Since the dataset is unbalanced we can use certain operations such as Horizontal Flip, Rotations, etc to account for this imbalance. This is known as Data Augmentation. The code below performs the same apart from converting the input into tensors and normalizing them. The values passed in for the normalization operation is standard for models trained on the ‘Image Net’ data. As stated earlier, we’ll be using transfer learning and I’ll explain more about this in the subsequent sections.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/535a960ec12ec6548a620cce67ce1531/href">https://medium.com/media/535a960ec12ec6548a620cce67ce1531/href</a></iframe><p>Also, do note that we do not perform certain operations on the test set or validation set as these, if applied, would lead to erroneous results.</p><p>We are going to load the data in batches. The following code utilizes the Dataloader class under torch.utils.data to do the same as shown below. The show batch function helps us visualize a batch of the image data after all the transforms have been applied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f03be0285934a11a122797df557c272f/href">https://medium.com/media/f03be0285934a11a122797df557c272f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*juQIyQ7qnHZBm_GT_ZjTaQ.png" /><figcaption>Batch of Training Data — Image by Author</figcaption></figure><p>We have the option to train our model using the GPU if such a compatible (CUDA enabled) component is present in your system. Deep Learning models are computationally intensive and it is usually better to train the models using a GPU instance as it leads to a quicker training time. The following helper functions aid us in determining whether a GPU is present and moves the data into it if one is indeed present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b5aa09e215d27aede4b51aa0e07a28/href">https://medium.com/media/b6b5aa09e215d27aede4b51aa0e07a28/href</a></iframe><p>Our data has now been pre-processed and is ready to be fed into the model. So, let’s talk a bit about the process involved in training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a0974db4fb6bad188e452af3b8dfa91/href">https://medium.com/media/3a0974db4fb6bad188e452af3b8dfa91/href</a></iframe><p>A batch of the data is passed into the model and a forward-pass is performed. The loss is calculated between the predicted and actual values. The loss function I’ve used here is cross entropy which can be found in the torch.nn.functional module. The loss values are used in the calculation of gradients which are further utilized to update the parameters of the model to improve it’s performance. All this process is done for some number of ‘epochs’. ‘Epochs’ is the number of times the model sees the entire training data.</p><p>As promised, let’s have a small discussion on transfer learning. As you know, there have been several research works in the field of Deep Learning. These works have led to the creation of novel architectures that perform well in tasks such as classification, object detection, segmentation, etc. Though we can create and use our own model architecture it rarely gives us very good results. One alternative for this is to use a model that was pre-trained on another dataset. We take that model’s architecture and weights and modify/tune the final layers according to our needs. This is known as ‘Transfer Learning’. You can read more about this <a href="https://machinelearningmastery.com/transfer-learning-for-deep-learning/">here</a>.</p><p>I chose to use the VGG16 model and build upon it to achieve the classification mechanism required for my task. Note that I also move the model to the GPU. Always ensure that both the data and the model are in the same instance (be it CPU or GPU). This is shown in the code snippet given below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c12996ab8d5692c6af0ff0a7ad23e9e/href">https://medium.com/media/6c12996ab8d5692c6af0ff0a7ad23e9e/href</a></iframe><p>Now that we have both our model and data, we create two more functions. One to train the model and another to evaluate the model. The fit function defined below aids us in training the model with the specified optimizer and learning rate for the stated epochs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90cb4499593cfb50f332d3a3cde83ab6/href">https://medium.com/media/90cb4499593cfb50f332d3a3cde83ab6/href</a></iframe><p>I chose the Adam optimizer for it’s known performance and faster convergence rate. The model was trained with the learning rates of 0.001 and 0.0001 for 5 epochs each. Though we only trained the model for a small number of epochs, it achieved a validation accuracy of 93.5%. That’s the advantage of employing transfer learning !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7172897712ba1c1033dd991159d07ea/href">https://medium.com/media/a7172897712ba1c1033dd991159d07ea/href</a></iframe><p>The major part of developing a model such as this one is it’s performance on unseen data. This is the ‘Test Set’ which has a diverse range of data that closely models the real world. The model we developed in this article achieved an accuracy of around 82% on the test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79b971109d37c209acf94aa78ab57b32/href">https://medium.com/media/79b971109d37c209acf94aa78ab57b32/href</a></iframe><p>An example where the model diagnosed incorrectly :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*kG0dNuFqj9NYw8lg7qoOlQ.png" /></figure><p>Though we obtained a decent level of accuracy, this is still not enough when it comes to deploying the model in real-time. We can further fine-tune the model or use other pre-trained model architectures to obtain better performance.</p><h4>Final Thoughts :</h4><ul><li>Before using a pre-trained model, I used a custom architecture of my own. It gave a training accuracy of 83% and test accuracy of 71%. Application of transfer learning increased the results greatly.</li><li>You can try out the ResNet series of architectures and see how the results fare in comparison.</li></ul><p>The notebook for this article can be found in this GitHub <a href="https://github.com/GSNCodes/Diagnosing_Pneumonia_PyTorch">repository </a>of mine. Feel free to fork/clone it to further improve the results yourselves.</p><p>~~ <em>G.SowmiyaNarayanan</em></p><p>I hope you found this article helpful and I’m glad to be a part of your journey :)</p><p>Feel free to comment and let me know what you think. You can also connect with me on <a href="https://www.linkedin.com/in/sowmiyanarayanan-g/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709e6d3b38c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/diagnosing-pneumonia-with-deep-learning-709e6d3b38c2">Diagnosing Pneumonia with Deep Learning</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection using YOLOv3]]></title>
            <link>https://medium.com/data-science/object-detection-using-yolov3-9112006d1c73?source=rss-150dc71378ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/9112006d1c73</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sowmiya Narayanan Govindaraj]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 14:48:07 GMT</pubDate>
            <atom:updated>2020-06-24T07:24:26.822Z</atom:updated>
            <content:encoded><![CDATA[<h4>A journey into detecting objects in real-time using YOLOv3 and OpenCV</h4><p>Deep learning has revolutionized the realm of computer vision. Neural Networks are widely used in almost all of the cutting-edge tech such as Tesla’s auto-pilot feature. They perform too well that there are times they lead to ethical issues and conflicts. Well, we won’t be diving into those today. Let’s focus on a sub-category of computer vision called “Detection”.</p><p>What does one mean by detecting an object? When we see an object, we can exactly point where it is and determine what it is with ease. For computers though, the task is not so simple. This has been an active area of research for years and continues to be so today. In the past decade, with the advent (rather the resurgence) of deep learning we were able to achieve good results to an extent that it has been possible to use it in real-time scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*kJcsE7xrRzbbb4-qCkMWgg.jpeg" /><figcaption>Image from <a href="https://en.wikipedia.org/wiki/Object_detection">Wikipedia</a></figcaption></figure><h4>Overview</h4><p>There are several Neural Network architectures for detection:-</p><ul><li>R-CNN family of architectures</li><li>Single Shot Detectors</li><li>YOLO — You Only Look Once</li></ul><p>We will today be seeing the implementation of YOLOv3(A variant of the original YOLO architecture) without going into much details as to how it works. The language of choice is Python(❤) because of it’s huge support from libraries such as OpenCV. Another important point worth mentioning is that the YOLO models are not as accurate as R-CNN models but they are swift and are easily suitable for real-time applications.</p><h4>Implementation</h4><p>Let’s begin by importing the necessary libraries. The OpenCV library is going to be our best friend for this tutorial as it has several helpful functions for manipulating images as well as useful modules such as ‘dnn’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bce8e9dd6645aaea70cb748f8eef4a18/href">https://medium.com/media/bce8e9dd6645aaea70cb748f8eef4a18/href</a></iframe><p>Since we’ll be using a pre-trained model, we’d have to download certain files. The “weights” file , the “configuration” file, and the “coco-names” file. The weights and the configuration file can be found in this <a href="https://pjreddie.com/darknet/yolo/">link </a>and the coco-names file can be downloaded/copied from <a href="https://github.com/pjreddie/darknet/blob/master/data/coco.names">here</a>. There are several pre-trained models available and we would be using the “YOLOv3–416&quot; model. The models are trained on the MS COCO dataset which has 80 classes of objects present in it.</p><p>After downloading all the files, its time to create and load our model. As you can see below, the dnn module has several functions in-built to aid us in this regard. The names of the objects that our model has been trained to identify is given in the “coco.names” file, which we store in a list called classes. We also retrieve the names of the output layers with the help of the <strong>getLayerNames()</strong> and <strong>getUnconnectedOutLayers()</strong> function and store them too in output_layers list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b17f9e41c7d64579bb2d4d20a883930f/href">https://medium.com/media/b17f9e41c7d64579bb2d4d20a883930f/href</a></iframe><p>We now have to pass-in the image through our model. But, we cannot do so directly as our model expects our image to be of a particular shape. This is where the <strong>cv2.dnn.blobFromImage()</strong> function comes in handy. It helps us to reshape our image while also normalizing them and re-ordering the color channels in proper order.</p><p>The image is then given to the model and a forward-pass is performed. The output of which gives us a list of detections. From this list a set of bounding-box co-ordinates for each object detected is obtained as shown below. We use a confidence threshold value to filter out weak detections. The default value I’ve used for confidence threshold is ‘0.5’. All the bounding-box co-ordinates, their class-ids and their corresponding confidence values are stored in lists “boxes”, “class_ids ”and “confidences” respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a50bb216d2ef66b8a130444a43a422/href">https://medium.com/media/06a50bb216d2ef66b8a130444a43a422/href</a></iframe><p>Now that we have obtained the locations of objects in our image, it’s time to sketch their bounding-box and tag them. The <strong>draw_boxes()</strong> function does this for us. One problem that we might encounter in our journey is that, the objects, sometimes, may be detected more than once. To avoid such a scenario, we’ll employ Non-Maximum Suppression (aka Non-Maxima Suppression). The default value I’ve used for NMS threshold is ‘0.4’. This is what is performed by the<strong> cv2.dnn.NMSBoxes()</strong> function down below. We finally display the output image using the <strong>cv2.imshow()</strong> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b2e1e5716742b29e95b4979e97b6e2c/href">https://medium.com/media/3b2e1e5716742b29e95b4979e97b6e2c/href</a></iframe><p>Now that we have seen all the components required, let us now glue it all together to perform object detection in an image file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f9fc24d56320d626a3260f523a1249e/href">https://medium.com/media/9f9fc24d56320d626a3260f523a1249e/href</a></iframe><p>We can perform the same task in videos from files as well as from web-cams as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56efafffd146cee62b35894042f8fc4b/href">https://medium.com/media/56efafffd146cee62b35894042f8fc4b/href</a></iframe><p>The image on the right shows multiple bounding-boxes around the same person. After employing NMS, we obtain the image on the left as output. The duplicate bounding-boxes have been dealt with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*PiVTxELjlYkbkGTmQc08ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*r6PrtUPr2thU3uxZRQZ2XA.png" /><figcaption>Sample Output — Test Image obtained from <a href="http://cocodataset.org/">http://cocodataset.org/</a></figcaption></figure><p>The entire code for this article along with a clean interface for you to build upon could be found in my GitHub repository through the link given down below.</p><p><a href="https://github.com/GSNCodes/YOLOv3_Object_Detection_OpenCV">https://github.com/GSNCodes/YOLOv3_Object_Detection_OpenCV</a></p><p>Recent advances in Deep Learning has opened up a lot of avenues for research and exploration. If you are thinking to dive deep into the same, I encourage you to do so. Create and innovate new tech but do so ethically. I hope you found this article helpful and I’m glad to be a part of your journey :)</p><p>~~ <em>G.SowmiyaNarayanan</em></p><p><strong>P.S. : —</strong></p><p>This is my first article on Medium and I am open to any sorts of criticism to improve my work so that I can better cater to the needs of explorers such as yourself in the future. Feel free to comment and let me know what you think. You can also connect with me on <a href="https://www.linkedin.com/in/sowmiyanarayanan-g/">LinkedIn</a>.</p><p><strong>MindBytes:-</strong></p><p><em>“If Nothing Changes, Nothing Changes.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9112006d1c73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/object-detection-using-yolov3-9112006d1c73">Object Detection using YOLOv3</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>