<?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 Chirag Shetty on Medium]]></title>
        <description><![CDATA[Stories by Chirag Shetty on Medium]]></description>
        <link>https://medium.com/@chirag4798?source=rss-d2c48d19b103------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XeAtImffwWY8GmjAfw3D_g.png</url>
            <title>Stories by Chirag Shetty on Medium</title>
            <link>https://medium.com/@chirag4798?source=rss-d2c48d19b103------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:48:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chirag4798/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[Who am I?]]></title>
            <link>https://chirag4798.medium.com/who-am-i-3fffea3ab951?source=rss-d2c48d19b103------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fffea3ab951</guid>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[free-will]]></category>
            <category><![CDATA[spinoza]]></category>
            <category><![CDATA[consciousness]]></category>
            <category><![CDATA[advaitavedanta]]></category>
            <dc:creator><![CDATA[Chirag Shetty]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 19:07:19 GMT</pubDate>
            <atom:updated>2026-10-25T19:22:10.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKOmWDXZdIukbll6" /><figcaption>Photo by <a href="https://unsplash.com/@zain_567?utm_source=medium&amp;utm_medium=referral">Zain Rauf</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Simple. I am Chirag Shetty.</p><p>That’s just your name. If I gave you a different name, would you become a different person?</p><p>No. I’d still be me. My body and my mind.</p><p>What if you had an accident and lost all bodily function and brain activity? Would you still be you?</p><p>I think so.</p><p>Let me ask it another way. If I wanted to replicate you as closely as possible, what would I need to replicate?</p><p>Interesting. Maybe my thoughts and actions.</p><p>If a robot were operated by your brain, would you consider it to be you?</p><p>Yes, I think so. If it did exactly what I would do in a given situation.</p><p>So I’d need to replicate your brain and thoughts, attach them to a humanoid robot that looks like you, and call it a day?</p><p>Perfect.</p><p>But can you control your thoughts?</p><p>Yes, I can.</p><p>As you read this sentence, is there a voice in your head saying the words?</p><p>Yes.</p><p>Can you predict your next thought before you think it?</p><p>Umm… that makes me uncomfortable.</p><p>Let’s try something else. Stop reading this sentence in your head.</p><p>Did you stop?</p><p>STOP READING RIGHT NOW!</p><p>No? You can’t?</p><p>What’s going on? What does this mean?</p><p>Is free will a myth? Spinoza would say we feel free because we know what we want, but not the causes that made us want it. Maybe we don’t choose which thought appears next, but that doesn’t mean our choices are meaningless. It may mean freedom has less to do with being uncaused and more to do with understanding what moves us.</p><p>That process carries the imprint of our experiences, our bodies, and thousands of years of evolution. It helps us make sense of the world and decide what to do, often before we can explain why we thought or acted that way.</p><p>We like to think we’re separate from nature because we’re conscious. But what is the difference between us and an animal acting on instinct? Maybe our instincts pass through a more complicated process before becoming actions. But how much control do we really have over that process?</p><p>Are we separate from nature?</p><p>These questions have been explored in different ways by Advaita Vedānta and Spinoza.</p><p>In Advaita Vedānta, the self we usually think of as “me” is not the deepest self. Our thoughts, feelings, memories, and body keep changing. Advaita asks us to look at the awareness through which we experience those changes. It teaches that our deepest self, ātman, is not separate from Brahman, ultimate reality.</p><p>That doesn’t quite mean that every thought in our head is the thought of the universe. Advaita distinguishes the changing mind from the awareness through which the mind is known. The question becomes less “Am I my thoughts?” and more “What is the awareness in which these thoughts appear?”</p><p>In Spinoza’s philosophy, there is one underlying substance, which he calls God, or Nature. Everything that exists, including us, is part of this reality. Our minds and bodies are not two separate things, with one controlling the other. They are two ways of understanding the same individual. Our thoughts, like our bodies, belong to nature and are shaped by causes.</p><p>There’s a similarity between the two: neither treats the everyday, individual self as completely independent from a deeper reality. But they don’t say exactly the same thing. Advaita focuses on the identity of ātman and Brahman, and on awareness as fundamental. Spinoza focuses on one substance, God or Nature, expressed in different ways, including thought and physical extension. Advaita’s ultimate reality is not simply the physical universe, and Spinoza’s God is not a creator standing outside nature.</p><p>Maybe our thoughts are not separate from nature. Maybe they are one of the ways nature moves through us.</p><p>And if we experience nature, could that be nature experiencing itself? Wouldn’t you say?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fffea3ab951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shop The Look]]></title>
            <link>https://chirag4798.medium.com/shop-the-look-8d686bde7de8?source=rss-d2c48d19b103------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d686bde7de8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[yolov5]]></category>
            <dc:creator><![CDATA[Chirag Shetty]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 13:53:09 GMT</pubDate>
            <atom:updated>2023-01-11T13:54:36.706Z</atom:updated>
            <content:encoded><![CDATA[<p>End-to-end content based fashion product recommendation engine based on visual similarity of items.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYlWKfkpZ9h0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYlWKfkpZ9h0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYlWKfkpZ9h0%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/edb61cc30a61eab483d2683d3c70873f/href">https://medium.com/media/edb61cc30a61eab483d2683d3c70873f/href</a></iframe><p>This blog is inspired by the research paper published by Myntra</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hpqvwA1CHYdVpsDL" /></figure><p><a href="https://arxiv.org/pdf/2008.11638.pdf">Buy Me That Look: An Approach for Recommending Fashion Products</a></p><h3>Introduction</h3><p>Have you ever looked at a model and wondered if you could ever look like him/her? Ever wondered how to develop a good fashion sense? Don’t worry this blog has a very elaborate (a bit much if you ask me) solution to both of those questions. The rise of e-commerce websites in India has led to an increase in online shopping throughout the country. Fashion items are the most sought after in the e-commerce market. A robust, effective, and efficient recommendation system for fashion items could lead to an increase in revenue, better customer engagement, and experience. What makes this approach novel is the ability to detect multiple products from a given Product Display page and recommend similar items to the user. A Product Display Page (PDP), is a web-page that presents an image of the product/products worn by a model or a standalone picture of the product in a plain background. This approach helps the user to not only look for the relevant item in a single category but also to match those items with other items that go well with the specified product. In simple words, thanks to the advancements in computer vision, you can copy the look of your favourite celebrity by just using an image of that look.</p><h3>Proposed Solution</h3><p>The proposed solution is a Content-Based recommendation system that involves various modules that carry specific tasks that help in achieving the overall goal. For the system proposed in the published article by Myntra the first module consists of the Human Key Point Detection, looks for specific human key points like the ankle and the eyes in order to classify the image as a full-shot image i.e. an image that consists of the full body of a model, however the solution proposed in this blog skips this step, instead we’ll recommend items using all the fashion products detected in an image. For better product recommendation we’ll first try to determine the gender of the person in the query image. The pose can either be front, back, left, right or detailed. After determining the gender, the input is fed is then fed to the next module, it’s an Object Detection module trained to identify objects from these broad categories — top-wear, bottom-wear, and foot-wear. The goal of this module is not just the identification of these objects in the image but also to localize the objects with bounding-boxes. Once the bounding boxes are obtained for a certain object, that part of the image is cropped and the semantic embeddings for the cropped image are obtained, which will help in identifying similar products from the catalog/database of products whose semantic embeddings are already known. We’ll train a Siamese Network for generating the embeddings for the catalog of images. This system helps in automatically and efficiently recommending new items to a user who has selected or shown interest in a certain product display page.</p><h3>Data Acquisition</h3><p>To get started with the Fashion Recommendation Engine, we’ll need a catalog/database consisting of fashion products to recommend. Unless you have a database of these items lying around we’ll need to acquire this data using simple web scraping tools in python. Since we’ll focus on recommending items across various categories we’ll need a diverse set of fashion products to populate the database. We can use Myntra’s e-commerce website to query images using specific keywords and later save the product details for the results obtained. This way we can categorize products into various sections which would make it easier while recommending items. We’ll use Selenium package from python, its the most popular browser automation tool mainly used to carry out web-product testing. For that we’ll require web-driver, for chrome users, you can get it from <a href="https://chromedriver.chromium.org/">here</a>, make sure the version that you download matches with the version of chrome on your computer. For more details on web-scraping e-commerce websites using python follow this article “<a href="https://medium.com/analytics-vidhya/web-scraping-e-commerce-sites-using-selenium-python-55fd980fe2fc">Web-scraping e-commerce websites using python</a>”. After scraping the image and product urls, you either use it to download the images into your local system or save the image and product urls pair to a flat file and use it later.</p><pre># import necessary libraries<br>import time<br>from selenium import webdriver as wb</pre><pre># Enter the path to your webdriver&#39;s .exe file here<br>wd = wb.Chrome(&#39;chromedriver.exe&#39;)</pre><pre># List of search terms to use for querying from the e-commerce sites<br>search_terms = [&quot;Mens Topwear&quot;, &quot;Womens Topwear&quot;, &quot;Mens Bottomwear&quot;, &quot;Womens Bottomwear&quot;, &quot;Mens Footwear&quot;, &quot;Womens Footwear&quot;]</pre><pre># Define the Maximum number of products you want to scrape per search term<br>MAX_PRODUCTS_PER_CATEGORY = 1000<br>image_urls, product_urls = list(), list()<br>for search_term in search_terms:<br>    search_term = search_term.lower()<br>    query = f&quot;https://www.myntra.com/{search_term.replace(&#39; &#39;, &#39;-&#39;)}&quot;<br>    total = 0<br>    wd.get(query)<br>    while total &lt; MAX_PRODUCTS_PER_CATEGORY:<br>        time.sleep(3)<br>        products = wd.find_elements_by_class_name(&quot;product-base&quot;)<br>        for product in products:<br>            try:<br>                image = product.find_element_by_tag_name(&quot;img&quot;)<br>            except:<br>                continue<br>            image_urls.append(image.get_property(&quot;src&quot;))<br>            product_urls.append(product.find_element_by_tag_name(&quot;a&quot;).get_property(&quot;href&quot;))<br>    try:<br>        wd.find_element_by_class_name(&quot;pagination-next&quot;).click()<br>    except:<br>        break</pre><h3>Exploratory Data Analysis</h3><p>Now that we’ve gathered the catalog, lets do some exploratory analysis on it. The dataset consists of 10310 fashion products in various categories. The categories being:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ILaTxAgJ6OwujFEM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hv7zR_8a-CdOleuI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q5MaF-DrTI-kYPiK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xgo1jb5wm4tsyApJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dWMtxYhD0l14Rm5J" /></figure><p>The fashion products are not equally split among the two genders, there are 5992 Mens Products whereas as just 4318 Womens products. The plot below is a visual representation of the products split by genders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*pUKA_CMweagUY0UO" /></figure><p>Distribution across the categories of Topwear — 3770, Bottomwear — 3524 and Footwear — 3016.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*oTRR5PxJMBDXoSSk" /></figure><p>There is huge disparity in the distribution among the type of clothing. Around 60% of the fashion items are of type casual whereas formal and party wear occupy just 30% and 10% respectively. The recommendations for casual would obviously be better considering the variety of items present in them. Here’s a visual representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*4lv09oHaO_wivfpP" /></figure><h3>Gender Classification</h3><p>In order to recommend relevant items to the user we’ll have to first detect the gender of the person present in the query image. Doing so will allow us to generate and query embeddings only on certain subsets of the catalog instead of the whole database. This will also help us in reducing irrelevant recommendations to the user based on their gender. For this task we’ll make use of the <a href="https://www.kaggle.com/playlist/men-women-classification">Man/Woman classification dataset from Kaggle</a>. This is a manually collected and cleaned dataset containing 3354 pictures (jpg) of men (1414 files) and women (1940 files) that includes full body and upper body images of men and women. This is ideal for our use case since we’ll mostly have full body images of models wearing various fashion items. For classification we can use a ResNET50 backbone initialized with ‘Imagenet’ weights attached to a fully connected network that outputs the probability scores for the two classes. We’ll freeze all the layers from the backbone since the task is comparitively easy to achieve and in order to avoid overfitting to this dataset. Below is a code snippet for the model used for classification. We are abe to achieve accuracy of 95% on the test set which is decent for our use case.</p><pre>from tensorflow.keras.models import Model<br>from tensorflow.keras.applications.resnet import ResNET50<br>from tensorflow.keras.layers import Flatten, Dense, Dropout, BatchNormalization</pre><pre>base_model = ResNet50(weights=&quot;imagenet&quot;, input_shape=(224,224,3), include_top=False)</pre><pre>for layer in base_model.layers:<br>    layer.trainable = False</pre><pre>x = Flatten()(base_model.output)<br>x = Dense(512, activation=&quot;relu&quot;)(x)<br>x = Dropout(0.3)(x)<br>x = BatchNormalization()(x)<br>x = Dense(128, activation=&quot;relu&quot;)(x)<br>x = Dropout(0.3)(x)<br>x = BatchNormalization()(x)</pre><pre>output = Dense(1, activation=&quot;sigmoid&quot;)(x)</pre><pre>gender_classifier = Model(base_model.input, output, name=&quot;Gender_Classifier&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*2oxRrKEeANuXfDLg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*kZULh1H95thOUm7F" /></figure><h3>Object Detection &amp; Localization</h3><p>In order to recommend similar products we’ll first need to detect all the products in a given image, and for generating the embeddings we’ll need to crop out the product from an image. Object detection is one of the most interesting aspect of Computer Vision. Most object detection systems have some kind of trade off between inference speed and detection accuracy. In order to better understand object we’ll need to understand a metric called ‘mAP’ or Mean Average Precision, for object detection whether a detection is considered correct or not depends on the IoU (Intersection over Union) threshold. The IoU score for a predicted bounding box and actual bounding box is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*CwxkuHuwWF0N_ME9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mvYSayhuadvSqQuW" /></figure><p>For a pre-defined IoU threshold we can define if a detection was accurate or not if the IoU is greater than the thresold. Based on the detections Precision and Recall is defined as.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*OVUONO8xcoi-ilNi" /></figure><p>Where TP = True Positive, FP = False Positive &amp; FN = False Negative</p><p>The average precision is calculated by using the Area Under the Precision and Recall Curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*EFwZLVGBgpzJ75UQ" /></figure><p>The Mean Average Precision is calculated by taking mean of the Average Precision values over different values of threshold, for example in the COCO Primary Challenge the mAP was calculated by averaging the AP scores over a range of IoU thresholds from 0.5 to 0.95 with a step size of 0.05 and finally taking the mean of the AP scores over all the classes. For more detailed explanation of mAP follow this blog — “<a href="https://towardsdatascience.com/breaking-down-mean-average-precision-map-ae462f623a52">Breaking Down Mean Average Precision</a>”. Now that we know how Object Detection Systems are evaluated let’s checkout various methods for object detection. We’ll compare various object detection model’s performance against the MS COCO Dataset that contains 80 classes. We’ll look at the Inference speed and mAP scores. Below is a plot showing the highest and lowest Frames Per Second (FPS) values reported in their respective papers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ui6qzm9uUxXIAlDh" /></figure><p><a href="https://jonathan-hui.medium.com/object-detection-speed-and-accuracy-comparison-faster-r-cnn-r-fcn-ssd-and-yolo-5425656ae359">Source: Object Detection Speed and Accuracy Comparison</a></p><p>It is clear that YOLO object detection are faster by a huge margin compared to other object detection methods, however an important thing to note is the plot doesn’t mention the mAP scores for the models with the highest inference speeds. Now lets look at mAP scores for various methods against the MS COCO Dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VHvy7uZWqZxdwyeO" /></figure><p><a href="https://jonathan-hui.medium.com/object-detection-speed-and-accuracy-comparison-faster-r-cnn-r-fcn-ssd-and-yolo-5425656ae359">Source: Object Detection Speed and Accuracy Comparision</a></p><p>From the plot above we can see that RetinaNET has the highest mAP score of 40.8 followed by Faster-RCNN, FPN and YOLO. The difference between the latter three methods is not huge compared to their difference with RetinaNET which is SOTA in object detection. We can safely assume that YOLO will provide us with the right balance of Accuracy and Speed for our task of Fashion product detection and localisation. The research paper by Myntra used Mask RCNN for their object detection module since they had the luxury to run that part offline, however we do not have that luxury if we want to recommend similar products in real time using a web application. Hence we’ll use YOLO object detection for detecting fashion products in three categories — topwear, bottomwear and footwear for our simplicity, we can easily improve our recommendation engine by including more and better categories for object detection like classifying the type of shirts, t-shirts, bags, sunglasses, trousers, jeans etc. YOLO refers to “You Only Look Once” is a versatile object detection model. YOLO algorithms divide a given input images into the SxS grid system. Each grid is responsible for object detection. Now the Grid cells predict the boundary boxes for the detected object. For every box, we have five main attributes: x and y for coordinates, w and h for width and height of the object, and a confidence score for that the box containing the object. Follow this blog for training an object detector using your custom dataset — “<a href="https://blog.roboflow.com/how-to-train-yolov5-on-a-custom-dataset/">YOLOv5 Training for Custom Dataset</a>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*BHUIhnmjc8-0YF_A" /></figure><p><a href="https://arxiv.org/pdf/1506.02640v1.pdf">Source: YOLO — You Only Look Once</a></p><p>Code snippet for training YOLOv5 model on custom dataset using PyTorch and Ultralytics Github repo.</p><pre>!git clone https://github.com/ultralytics/yolov5<br>%cd yolov5<br>%pip install -qr requirements.txt </pre><pre>import torch<br>print(&#39;Setup complete. Using torch %s %s&#39; % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else &#39;CPU&#39;))</pre><pre>!python train.py --img 640 --batch 2 --epochs 150 --data custom_dataset.yaml --weights /content/yolov5/weights/yolov5s.pt --nosave --cache</pre><p>Your ‘custom_dataset.yaml’ file should look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*ST-1F5yIEJkgSOnf" /></figure><p>For training the custom Object Detection model we’ll use Transfer Learning. We’ll load YOLOv5s (s stands for small variant of YOLOv5) weights trained on the COCO Dataset and use transfer learning to fine-tune the model for our use case. I’ve created a dataset of 180 images (135 train and 45 validation) with annotated topwear, bottomwear and footwear. We were able to achieve a mAP score of 0.94 @ 0.5 IoU threshold on a test set of 45 images. Here are some object detection results on topwear, bottomwear and footwear detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dfj7pPDOYP9rKneJ" /></figure><p>Training summary for Topwear, Bottomwear and Footwear detection and localization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*7JnS66tOL7oLGC7j" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*vnzClwwpsR7MuX4d" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*PyjH8X0fukuRW0_V" /></figure><h3>Embedding Generation</h3><p>We use embedding generation to represent images/products such that similar ones are grouped together whereas dissimilar ones are moved away so that in order to retrieve products that are similar to the products present in the query image. There are various ways to calculate similarity between images after they are converted into a vector with n-dimensions. Cosine similarity and Euclidean distance are two examples. We can define Cosine similarity and Euclidean distance as -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*Dq4PsviD7n7POl-J" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*exFXgDdiAft3u6_L" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/0*zxucp2YSFpOtQk52" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*JCNuD2CVcgF7VWRX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/0*X7r33ZkuTArMeBe6" /></figure><p>In order to convert images to n-dimensional vector representations of the images, we’ll use a special type of Neural Network called Siamese Network. It is network which takes in three inputs — anchor, positive and negative the inputs are such that anchor and positive inputs are similar whereas anchor and negative inputs are dissimilar. The output is three n-dimensional vectors representing anchor, positive and negative inputs generated by a CNN backbone. This network requires a special kind of loss function that minimises the distance metric between anchor and positive while maximising the distance metric between anchor and negative hence we’ll need an intermediate layer that computes the distance between anchor and positve outputs and anchor and negative outputs. One such loss is the triplet loss which in our case we’ve defined as -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y8E43nDSqugKiPkC" /></figure><p><a href="https://arxiv.org/pdf/2008.11638.pdf">Embeddings Learning</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*HUprQbNk3AwfXC2R" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*V3jjUXq54_W5RGDO" /></figure><p>“Shop The Look” is a dataset taken from “<a href="https://arxiv.org/pdf/1812.01748.pdf">Wang-Cheng Kang, Eric Kim, Jure Leskovec, Charles Rosenberg, Julian McAuley (2019). Complete the Look: Scene-based Complementary Product Recommendation</a>”. In Proceedings of IEEE Conference on Computer Vision and Pattern Recognition (CVPR’19). It provides the two datasets for fashion and home respectively with scene and product pairs. Product is an image of a product in professional setting whereas a scene is the image of the same product but in casual or non-professional setting. Each dataset contains the scene-product pairs in the following format, where scene and products are encoded with a signature that can be converted to an url by using a function provided in the official GitHub repo <a href="https://github.com/kang205/STL-Dataset">STL-Dataset</a>.</p><pre>Example (fashion.json):<br>{<br>    &quot;product&quot;: &quot;0027e30879ce3d87f82f699f148bff7e&quot;, <br>    &quot;scene&quot;: &quot;cdab9160072dd1800038227960ff6467&quot;, <br>    &quot;bbox&quot;: [<br>        0.434097, <br>        0.859363, <br>        0.560254, <br>        1.0<br>    ]<br>}</pre><p>We can easily create anchor and positive pairs from this dataset and for generating negative samples we can randomly select scenes from the dataset which is not same as the positive sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZAzlnkn-82isMQkV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mbu3x1YKvK_O9CDB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eMu_XTftk79vCP6G" /></figure><p>We now move onto to define the Siamese network using Tensorflow and Keras. For a detailed explanation on the definition of the network, follow this tutorial from <a href="https://keras.io/examples/vision/siamese_network/">Keras</a></p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Model<br>from tensorflow.keras import losses, metrics, optimizers<br>from tensorflow.keras.applications import resnet<br>from tensorflow.keras.layers import Input, Flatten, Dense, BatchNormalization</pre><pre>TARGET_SHAPE = (224,224,3)<br>base_model = resnet.ResNet50(weights=&quot;imagenet&quot;, input_shape=TARGET_SHAPE, include_top=False)</pre><pre>for layer in base_model.layers:<br>    layer.trainable = True</pre><pre>x = Flatten()(base_model.output)<br>x = Dense(512, activation=&quot;relu&quot;)(x)<br>x = BatchNormalization()(x)<br>x = Dense(256, activation=&quot;relu&quot;)(x)<br>x = BatchNormalization()(x)</pre><pre>output = Dense(EMBEDDING_DIMENSION, activation=&quot;linear&quot;)(x)</pre><pre>embedding = Model(base_model.input, output, name=&quot;Embedding&quot;)</pre><pre>class DistanceLayer(tf.keras.layers.Layer):<br>    &quot;&quot;&quot;<br>    This layer is responsible for computing the distance between the anchor<br>    embedding and the positive embedding, and the anchor embedding and the<br>    negative embedding.<br>    &quot;&quot;&quot;</pre><pre>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)</pre><pre>    def call(self, anchor, positive, negative):<br>        ap_distance = tf.reduce_sum(tf.square(anchor - positive), -1)<br>        an_distance = tf.reduce_sum(tf.square(anchor - negative), -1)<br>        return (ap_distance, an_distance)</pre><pre>anchor_input = Input(name=&quot;anchor&quot;, shape=TARGET_SHAPE)<br>positive_input = Input(name=&quot;positive&quot;, shape=TARGET_SHAPE)<br>negative_input = Input(name=&quot;negative&quot;, shape=TARGET_SHAPE)</pre><pre>distances = DistanceLayer()(embedding(resnet.preprocess_input(anchor_input)), embedding(resnet.preprocess_input(positive_input)), embedding(resnet.preprocess_input(negative_input)))</pre><pre>siamese_network = Model(inputs=[anchor_input, positive_input, negative_input], outputs=distances)</pre><pre>class SiameseModel(Model):<br>    &quot;&quot;&quot;The Siamese Network model with a custom training and testing loops.</pre><pre>    Computes the triplet loss using the three embeddings produced by the<br>    Siamese Network.</pre><pre>    The triplet loss is defined as:<br>       L(A, P, N) = max(‖f(A) - f(P)‖² - ‖f(A) - f(N)‖² + margin, 0)<br>    &quot;&quot;&quot;</pre><pre>    def __init__(self, siamese_network, margin=0.5):<br>        super(SiameseModel, self).__init__()<br>        self.siamese_network = siamese_network<br>        self.margin = margin<br>        self.loss_tracker = metrics.Mean(name=&quot;loss&quot;)</pre><pre>    def call(self, inputs):<br>        return self.siamese_network(inputs)</pre><pre>    def train_step(self, data):<br>        with tf.GradientTape() as tape:<br>            loss = self._compute_loss(data)<br>        gradients = tape.gradient(loss, self.siamese_network.trainable_weights)<br>        self.optimizer.apply_gradients(zip(gradients, self.siamese_network.trainable_weights))<br>        self.loss_tracker.update_state(loss)<br>        return {&quot;loss&quot;: self.loss_tracker.result()}</pre><pre>    def test_step(self, data):<br>        loss = self._compute_loss(data)<br>        self.loss_tracker.update_state(loss)<br>        return {&quot;loss&quot;: self.loss_tracker.result()}</pre><pre>    def _compute_loss(self, data):<br>        ap_distance, an_distance = self.siamese_network(data)<br>        loss = ap_distance - an_distance<br>        loss = tf.maximum(loss + self.margin, 0.0)<br>        return loss</pre><pre>    @property<br>    def metrics(self):<br>        return [self.loss_tracker]<br>        <br>siamese_model = SiameseModel(siamese_network)<br>siamese_model.compile(optimizer=optimizers.Adam(1e-4))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*qu6qfYnRuiZPwH9P" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*jZtnmMSESrMnNvJR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*I9SpOmUoMiH5A9gp" /></figure><p>Having trained the embedding generation model, we have to generate and save embeddings for the catalog of fashion products.</p><h3>Final Pipeline</h3><p>Having generated and stored the embeddings for the catalog of fashion products, the final step is to combine all the modules into a pipeline that takes in a query image and outputs the relevant recommendations. Before we start predicting from our saved tensorflow models we can further optimize them by using a technique called post training quantization. Post-training quantization is a conversion technique that can reduce model size while also improving CPU and hardware accelerator latency, with little degradation in model accuracy. One can quantize an already-trained float TensorFlow model when its converted to TensorFlow Lite format using the TensorFlow Lite Converter. We will reduce the size of a floating point model by quantizing the weights to float16, it can virtually reduce the model size by half by converting all the float32 weights to float16. The below code snippet can be used to quantize Tensorflow-Keras models to Tensorflow-Lite models -</p><pre>import tensorflow as tf<br>from tensorflow.keras.models import load_model()</pre><pre># Path to your saved tensorflow-keras model<br>TFKERAS_MODEL_PATH = &quot;model.h5&quot;</pre><pre># Path to save the tensorflow-lite model<br>TFLITE_MODEL_PATH = &quot;model.tflite&quot;<br>model = load_model(TFKERAS_MODEL_PATH)</pre><pre>tf_lite_converter = tf.lite.TFLiteConverter.from_keras_model(model)<br>tf_lite_converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]<br>tf_lite_converter.target_spec.supported_types = [tf.float16]<br>tflite_model = tf_lite_converter.convert()</pre><pre>open(TFLITE_MODEL_PATH, &quot;wb&quot;).write(tflite_model)</pre><p>We can use the following code snippet to load and predict using a Tensorflow-Lite model.</p><pre>import tensorflow as tf</pre><pre>class TFLiteModel:<br>    &quot;&quot;&quot;<br>    Generic Class to load, initialise and predict using Tensorflow Lite Models<br>    &quot;&quot;&quot;<br>    def __init__(self, model_path, batch_size, input_shape, output_shape):<br>        &quot;&quot;&quot;<br>        Initialize interpretor, allocate input and output tensors<br>        &quot;&quot;&quot;<br>        self.interpreter = tf.lite.Interpreter(model_path=model_path)<br>        self.input_details = self.interpreter.get_input_details()<br>        self.output_details = self.interpreter.get_output_details()<br>        self.interpreter.resize_tensor_input(self.input_details[0][&#39;index&#39;], (batch_size,) + input_shape)<br>        self.interpreter.resize_tensor_input(self.output_details[0][&#39;index&#39;], (batch_size,) +  output_shape)<br>        self.interpreter.allocate_tensors()<br>        self.input_details = self.interpreter.get_input_details()<br>        self.output_details = self.interpreter.get_output_details()<br>        <br>    def __call__(self, X):<br>        &quot;&quot;&quot;<br>        Invoke the Tensorflow Lite model with the provided input and produce predictions/outputs<br>        &quot;&quot;&quot;<br>        self.interpreter.set_tensor(self.input_details[0][&#39;index&#39;], X)<br>        self.interpreter.invoke()<br>        y = self.interpreter.get_tensor(self.output_details[0][&#39;index&#39;])<br>        return y<br>        <br>tflite_model = TFLiteModel(model_path=TFLITE_MODEL_PATH, batch_size=32, input_shape=(224,224,3), output_shape=(256,))<br>outputs = tflite_model(inputs)</pre><p>Below are some plots showing the improvements in the models after Post Training Quantization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*TyIjZUZmm-KLi7YV" /></figure><p><a href="https://imgur.com/BZCxns7">Quantization Summary for Gender Classification Model</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*U1Kcd2sLSpxztEuo" /></figure><p><a href="https://imgur.com/FTcVAtU">Quantization Summary for Embedding Generation Model</a></p><p>After the models are optimized we can create the final pipeline as shown in the diagram below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Q97t85IuK9Pf3ca" /></figure><p>Here are some example recommendations from the final pipeline. The first image is the query image followed by the recommendations</p><p>Query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/0*Ghz7bfNAG18hbAL1" /></figure><p>Recommendation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*1EQ7dom0-ZgUgaEh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/0*xmBHC88wP50tHEKU" /></figure><p>Query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/0*Wn8yDdGVamsRIW8J" /></figure><p>Recommendation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*v0OCaQOyA9PYmrKd" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*GwvidQF1PYpZwz3K" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*jmn9xYCun55_fBKt" /></figure><p>Query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/0*ijwQohIen681vWCw" /></figure><p>Recommendation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*UU6_JNN3HzCfvt-s" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*OCYiHOfsB25Lq23K" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/0*1d9e348U7JqeCEE_" /></figure><p>Query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*QCngnbxNekLjv5iN" /></figure><p>Recommendation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*YIQVty0_n6r7j-iI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/0*Ux3_PQK4QO_Bz_tY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*pMND0vqPRFuLPs0o" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYlWKfkpZ9h0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYlWKfkpZ9h0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYlWKfkpZ9h0%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/edb61cc30a61eab483d2683d3c70873f/href">https://medium.com/media/edb61cc30a61eab483d2683d3c70873f/href</a></iframe><h3>Further Improvements &amp; Future Work</h3><p>This system can be considered as a POC (Proof of Concept) for image similarity based item recommendation engine, further improvements can be made by changing the existing modules with better performing alternatives as the time progresses. For example we can switch the object detection pipeline to any SOTA algorithms of the time for better detections. similarly we can retrain the embedding generation model regularly from time to time as new products are being added to the catalog. The current object detection only detects topwear, bottomwear and footwear we can improve it by adding specific classes instead of broad terms, like shirts, t-shirts, suits, pants, trouser, jeans, shoes and also support for other fashion accessories like handbags, sunglasses, watches etc. The STL-Dataset included lot of pairs where the product and the scene did not match, we can clean the dataset of such pairs and retrain the embedding generation model for higher number of epochs. Lastly we need to deploy this system for users to try it out.</p><h3>References</h3><ul><li><a href="https://www.appliedaicourse.com/course/11/Applied-Machine-learning-course">Applied AI Course’s Machine Learning Course</a></li><li><a href="https://arxiv.org/pdf/2008.11638.pdf">Buy Me That Look: An Approach for Recommending Fashion Products</a></li><li><a href="https://medium.com/analytics-vidhya/web-scraping-e-commerce-sites-using-selenium-python-55fd980fe2fc">Webscraping e-commerce websites using python</a></li><li><a href="https://www.kaggle.com/playlist/men-women-classification">Man/Woman classification dataset from Kaggle</a></li><li><a href="https://towardsdatascience.com/breaking-down-mean-average-precision-map-ae462f623a52">Breaking Down Mean Average Precision</a></li><li><a href="https://jonathan-hui.medium.com/object-detection-speed-and-accuracy-comparison-faster-r-cnn-r-fcn-ssd-and-yolo-5425656ae359">Object Detection Speed and Accuracy Comparision</a></li><li><a href="https://blog.roboflow.com/how-to-train-yolov5-on-a-custom-dataset/">YOLOv5 Training for Custom Dataset</a></li><li><a href="https://arxiv.org/pdf/1506.02640v1.pdf">YOLO — You Only Look Once</a></li><li><a href="https://github.com/ultralytics/yolov5">Ultralytics YOLOv5</a></li><li><a href="https://arxiv.org/pdf/1812.01748.pdf">Complete the Look: Scene-based Complementary Product Recommendation</a></li><li><a href="https://github.com/kang205/STL-Dataset">STL-Dataset</a></li><li><a href="https://keras.io/examples/vision/siamese_network/">Keras Tutorial for image similarity calculation</a></li></ul><h3>Contact Me</h3><ul><li><a href="https://github.com/chirag4798/Shop-The-Look">Code</a></li><li><a href="https://github.com/chirag4798">Github</a></li><li><a href="https://www.linkedin.com/in/chirag-shetty-85250913a/">Linkedin</a></li><li><a href="https://chirag4798.github.io/">Website</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d686bde7de8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nvidia DeepStream 101: A step-by-step guide to creating your first DeepStream application]]></title>
            <link>https://chirag4798.medium.com/nvidia-deepstream-101-a-step-by-step-guide-to-creating-your-first-deepstream-application-68148753cf96?source=rss-d2c48d19b103------2</link>
            <guid isPermaLink="false">https://medium.com/p/68148753cf96</guid>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deepstream]]></category>
            <dc:creator><![CDATA[Chirag Shetty]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 10:40:55 GMT</pubDate>
            <atom:updated>2023-01-11T10:40:55.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN2BvbWtm7yCIDdgO4aHrA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@opticonor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Conor Luddy</a> on <a href="https://unsplash.com/photos/IGa3Md8wP6g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Welcome back to our DeepStream tutorial series! In the <a href="https://chirag4798.medium.com/nvidia-deepstream-101-a-beginners-guide-to-real-time-computer-vision-afefcb5d7fba">last blog</a>, we covered the basics of DeepStream and how to get it up and running on your machine. Now it’s time to dive a little deeper into the world of DeepStream and see what it can do.</p><h3>What the heck is GStreamer?</h3><p>GStreamer is a powerful open-source multimedia framework that helps you build audio and video processing pipelines. And when it comes to DeepStream, GStreamer pipelines are kind of a big deal. They’re the driving force behind DeepStream, and they’re what allow you to process video streams in real-time.</p><p>But what makes up a GStreamer pipeline? Glad you asked! There are three main components: elements, loops, and pipelines.</p><p><strong>Elements: </strong>are the building blocks of GStreamer pipelines. They’re like the bricks and mortar of your pipeline, and they can do all sorts of cool stuff. An element is a single unit of functionality in GStreamer, such as reading a file or decoding a video stream. You can even create your own elements if you’re feeling ambitious (or just really, really need a specific element).</p><blockquote>What are elements?</blockquote><blockquote>For the application programmer, elements are best visualized as black boxes. On the one end, you might put something in, the element does something with it and something else comes out at the other side. For a decoder element, for example, you’d put in encoded data, and the element would output decoded data.</blockquote><p><a href="https://gstreamer.freedesktop.org/documentation/application-development/basics/elements.html?gi-language=c"><em>Elements in GStreamer</em></a></p><p>The Diagram below illustrates the most common type of elements that you’ll interact with while building a pipeline. There are three main types of elements in a GStreamer pipeline: source elements, filter elements, and sink elements. Source elements produce data, filter elements transform or modify data, and sink elements consume data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/0*rR5X4J0Nml8-YB9n.png" /><figcaption>A Filter element with one source pad and one sink pad</figcaption></figure><p><strong>Pads:</strong> The connections between elements are called pads, and they allow data to flow between elements. The pads are the element’s interface to the outside world. Data streams from one element’s source pad to another element’s sink pad. The specific type of media that the element can handle will be exposed by the pad’s capabilities. The terminology of source and sink is reversed in case of pads, the sink pad gets the input from upstream element whereas the source pad dumps the output to the downstream element. An element can have any number of sink and source pads depending on how it handles the data.</p><p><strong>Loops:</strong> as you might have guessed, allow you to loop over certain parts of your pipeline. They’re great for when you want to process a stream multiple times or when you need to do some kind of repetitive task. Just be careful not to get stuck in an infinite loop (unless you’re into that sort of thing).</p><p><strong>Pipeline:</strong> Finally, we have pipelines. But what makes up a GStreamer pipeline? Glad you asked! A GStreamer pipeline is essentially a directed acyclic graph (DAG) of elements that work together to process a video stream. The elements are connected together in a specific order to form a pipeline. The diagram below is an example for a GStreamer pipeline that uses DeepStream plugins (apologies for the small text).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KV-ihF-ruhiuFRIfoPddcw.png" /><figcaption>A GStreamer pipeline for Object Detection and Tracking that saves output to a mp4 file.</figcaption></figure><h3>How do you create a Pipeline in DeepStream?</h3><p>We’re gonna create a simple pipeline that takes in a mp4 file as input, does objects detection, tracking and displays the output in a mp4 file.</p><pre>filesrc -&gt; qtdemux -&gt; h264parse -&gt; nvv4l2decoder -&gt; nvstreammux -&gt; nvinfer -&gt; nvtracker -&gt; nvvideoconvert -&gt; nvdsosd -&gt; nvvideoconvert -&gt; nvv4l2h264enc -&gt; h264parse -&gt; qtmux -&gt; filesink</pre><ul><li><strong>filesrc</strong>: This element is used to read in the input mp4 file. The location attribute specifies the path to the input mp4 file on the system.</li><li><strong>qtdemux</strong>: This element is used to demultiplex the audio and video streams in the input mp4 file. It separates the audio and video streams into different pads, which can then be processed separately.</li><li><strong>h264parse</strong>: This element is used to parse the H.264 video stream from the qtdemux element. It extracts information such as frame rate and resolution, which is used to configure the video pipeline.</li><li><strong>nvv4l2decoder</strong>: This element is used to decode the H.264 video stream from the h264parse element. It converts the compressed video into raw video frames that can be processed by the pipeline.</li><li><strong>nvstreammux</strong>: This element is used to multiplex the video stream from the nvv4l2decoder element with the metadata streams generated by other elements in the pipeline. The batch-size attribute specifies the number of frames to be processed in each batch.</li><li><strong>nvinfer</strong>: This element is used to run the object detection model on the frames from the nvstreammux element. The config-file-path attribute specifies the path to the configuration file for the object detection model. We’re going to use the config path used by the deepstream-test-app1. Its a Resnet Caffe model that detects four classes.</li><li><strong>nvtracker</strong>: This element is used to track objects detected by the nvinfer element. The ll-lib-file attribute specifies the path to the library file for the multi-object tracking algorithm. We’re using the default tracker that is supplied with DeepStream — NvMultiObjectTracker.</li><li><strong>nvvideoconvert</strong>: This element is used to convert the video frames between different video formats (Nv12 and RGBA formats). It is used to convert the frames from the nvtracker element to a format that can be processed by the nvdsosd element.</li><li><strong>nvdsosd</strong>: This element is used to overlay the bounding boxes and labels on the video frames from the nvvideoconvert element. It draws the bounding boxes and labels on the frames based on the metadata generated by the nvtracker and nvinfer elements.</li><li><strong>nvv4l2h264enc</strong>: This element is used to encode the video frames from the nvvideoconvert element into H.264 format.</li><li><strong>h264parse</strong>: This element is used to parse the H.264 video stream from the nvv4l2h264enc element.</li><li><strong>qtmux</strong>: This element is used to multiplex the video and audio streams into an mp4 file.</li><li><strong>filesink</strong>: This element is used to write the output mp4 file to a location on the system. The location attribute specifies the path to the output file.</li></ul><p>First off, we got our trusty filesrc element, which is like the gatekeeper of the pipeline. It’s the one responsible for taking the mp4 file in and begin processing data to downstream elements. Next up, we have the qtdemux element, aka the party-starter. It separates the audio and video streams, so we can work on them separately. Then we got the h264parse element, the brain of the operation. It extracts all the important information like frame rate and resolution, so we can configure the video pipeline. Now, we got the nvv4l2decoder, it decodes the H.264 video stream and converts it into raw video frames for the pipeline to work its magic.</p><p>After that, we got the nvstreammux, the multitasker. It takes care of multiplexing multiple video stream with the metadata streams generated by other elements. We then got the nvinfer, it runs the object detection model on the frames and adds list of objects detected to the metadata of the pipeline. Next up, we got the nvtracker, the ninja of the pipeline. It tracks the objects detected by the nvinfer element.</p><p>Then we got the nvvideoconvert, it converts the video frames between different video formats so nvdsosd can work seamlessly. After that, we got the nvdsosd, the artist of the pipeline. It overlays the bounding boxes and labels on the video frames. Then we got another nvvideoconvert, to revert it back to a format that can be accepted by downstream elements. Now, we got the nvv4l2h264enc, it encodes the video frames into H.264 format and prepares the output file. We then got the h264parse element, the quality checker. It parses the H.264 video stream one last time to make sure everything is perfect. Lastly, we got the qtmux and filesink element, the dynamic duo. They multiplex the video and audio streams into an mp4 file and save it to a location on the system, so we can all enjoy the final output.</p><h3>Code!!!</h3><p>Here’s the <a href="https://github.com/chirag4798/DeepStream101/">code for creating the GStreamer and DeepStream pipeline in C</a> on GitHub. Include necessary gstreamer, glib and DeepStream header files. Define some constants for nvstreammux output width, height and batch-timeout (Don’t worry we’ll go in detail about these properties in the upcoming series).</p><pre>#include &lt;gst/gst.h&gt;<br>#include &lt;glib.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;cuda_runtime_api.h&gt;<br>#include &quot;gstnvdsmeta.h&quot;<br><br>/* The muxer output resolution must be set if the input streams will be of<br> * different resolution. The muxer will scale all the input frames to this<br> * resolution. */<br>#define MUXER_OUTPUT_WIDTH 1920<br>#define MUXER_OUTPUT_HEIGHT 1080<br><br>/* Muxer batch formation timeout, for e.g. 40 millisec. Should ideally be set<br> * based on the fastest source&#39;s framerate. */<br>#define MUXER_BATCH_TIMEOUT_USEC 40000</pre><p>We’ll initialise all the elements of the pipeline</p><pre>GMainLoop *loop = NULL;<br>GstElement *pipeline = NULL, *source = NULL, *h264parser = NULL, *nvv4l2h264enc = NULL, *qtdemux = NULL,<br>           *nvv4l2decoder = NULL, *streammux = NULL, *sink = NULL, *nvvidconv = NULL, *qtmux = NULL,<br>           *pgie = NULL, *tracker = NULL, *nvvidconv2 = NULL, *nvosd = NULL, *h264parser2 = NULL;<br><br>GstElement *transform = NULL;<br>GstBus *bus = NULL;<br>guint bus_watch_id;<br><br>/* Check input arguments */<br>if (argc != 2) {<br>  g_printerr (&quot;Usage: %s &lt;/path/to/input/video.mp4&gt;\n&quot;, argv[0]);<br>  return -1;<br>}</pre><p>The pipeline starts by creating a GMainLoop, which is the main event loop in Gstreamer, and a GstElement pipeline, which is the main pipeline that connects all the elements. We need to initialise GStreamer with gst_init (&amp;<em>argc</em>, &amp;<em>argv</em>); , initialise the loop with loop = g_main_loop_new (NULL, FALSE); .</p><pre>/* Standard GStreamer initialization */<br>gst_init (&amp;argc, &amp;argv);<br>loop = g_main_loop_new (NULL, FALSE);</pre><p>The pipeline elements are created using the gst_element_factory_make function, which creates an instance of the specified element.</p><pre>/* Create gstreamer elements */<br>/* Create Pipeline element that will form a connection of other elements */<br>pipeline = gst_pipeline_new (&quot;deepstream_tutorial_app1&quot;);<br><br>/* Input File source element */<br>source = gst_element_factory_make (&quot;filesrc&quot;, &quot;file-source&quot;);<br><br>/* QTDemux for demuxing different type of input streams */<br>qtdemux = gst_element_factory_make (&quot;qtdemux&quot;, &quot;qtdemux&quot;);<br><br>/* Since the data format in the input file is elementary h264 stream,<br>* we need a h264parser */<br>h264parser = gst_element_factory_make (&quot;h264parse&quot;, &quot;h264-parser&quot;);<br><br>/* Use nvdec_h264 for hardware accelerated decode on GPU */<br>nvv4l2decoder = gst_element_factory_make (&quot;nvv4l2decoder&quot;, &quot;nvv4l2-decoder&quot;);<br><br>/* Create nvstreammux instance to form batches from one or more sources. */<br>streammux = gst_element_factory_make (&quot;nvstreammux&quot;, &quot;stream-muxer&quot;);<br><br>/* Use nvinfer to run inferencing on decoder&#39;s output,<br>* behaviour of inferencing is set through config file */<br>pgie = gst_element_factory_make (&quot;nvinfer&quot;, &quot;primary-nvinference-engine&quot;);<br><br>/* Assigns track ids to detected bounding boxes*/<br>tracker = gst_element_factory_make (&quot;nvtracker&quot;, &quot;tracker&quot;);<br><br>/* Use convertor to convert from NV12 to RGBA as required by nvosd */<br>nvvidconv = gst_element_factory_make (&quot;nvvideoconvert&quot;, &quot;nvvideo-converter&quot;);<br><br>/* Create OSD to draw on the converted RGBA buffer */<br>nvosd = gst_element_factory_make (&quot;nvdsosd&quot;, &quot;nv-onscreendisplay&quot;);<br><br>/* Use convertor to convert from NV12 to RGBA as required by nvosd */<br>nvvidconv2 = gst_element_factory_make (&quot;nvvideoconvert&quot;, &quot;nvvideo-converter2&quot;);<br><br>/* Use convertor to convert from NV12 to H264 as required */<br>nvv4l2h264enc = gst_element_factory_make (&quot;nvv4l2h264enc&quot;, &quot;nvv4l2h264enc&quot;);<br><br>/* Since the data format for the output file is elementary h264 stream,<br>* we need a h264parser */<br>h264parser2 = gst_element_factory_make (&quot;h264parse&quot;, &quot;h264parser2&quot;);<br><br>qtmux = gst_element_factory_make (&quot;qtmux&quot;, &quot;qtmux&quot;);<br><br>sink = gst_element_factory_make (&quot;filesink&quot;, &quot;filesink&quot;);<br><br>if (!pipeline || !source || !h264parser || !qtdemux ||<br>    !nvv4l2decoder || !streammux || !pgie || !tracker || <br>    !nvvidconv || !nvosd || !nvvidconv2 || !nvv4l2h264enc || <br>    !h264parser2 || !qtmux || !sink) {<br>  g_printerr (&quot;One element could not be created. Exiting.\n&quot;);<br>  return -1;<br>}</pre><p>We need to set properties to the element using g_object_set function.</p><pre><br>/* we set the input filename to the source element */<br>g_object_set (<br>  G_OBJECT (source), <br>  &quot;location&quot;, <br>  argv[1], <br>  NULL<br>);<br><br>g_object_set (<br>  G_OBJECT (streammux), <br>  &quot;batch-size&quot;, <br>  1, <br>  &quot;width&quot;, <br>  MUXER_OUTPUT_WIDTH, <br>  &quot;height&quot;,<br>  MUXER_OUTPUT_HEIGHT,<br>  &quot;batched-push-timeout&quot;, <br>  MUXER_BATCH_TIMEOUT_USEC, NULL<br>);<br><br>/* Set all the necessary properties of the nvinfer element,<br>* the necessary ones are : */<br>g_object_set (<br>    G_OBJECT (pgie),<br>    &quot;config-file-path&quot;, <br>    &quot;/opt/nvidia/deepstream/deepstream/sources/apps/sample_apps/deepstream-test1/dstest1_pgie_config.txt&quot;, <br>    NULL<br>  );<br><br>/* Set all the necessary properties of the nvtracker element,<br>* the necessary ones are : */<br>g_object_set (<br>    G_OBJECT (tracker),<br>    &quot;ll-lib-file&quot;, <br>    &quot;/opt/nvidia/deepstream/deepstream/lib/libnvds_nvmultiobjecttracker.so&quot;, <br>    NULL<br>  );<br><br>/* Set output file location */<br>g_object_set (<br>    G_OBJECT (sink),<br>    &quot;location&quot;, <br>    &quot;output.mp4&quot;, <br>    NULL<br>  );</pre><p>Before linking the elements together, the elements need to be added to the same GST_BIN .</p><pre>/* Set up the pipeline */<br>/* we add all elements into the pipeline */<br>gst_bin_add_many (<br>  GST_BIN (pipeline),<br>  source,<br>  qtdemux,<br>  h264parser,<br>  nvv4l2decoder,<br>  streammux, <br>  pgie,<br>  tracker,<br>  nvvidconv, <br>  nvosd,<br>  nvvidconv2,<br>  nvv4l2h264enc,<br>  h264parser2,<br>  qtmux,<br>  sink, <br>  NULL<br>);</pre><p>Not all elements in pipeline can be linked together with gst_link_many function. For eg. the video_%u pad and audio_%u pad on the qtmux element are created when the audio and video streams are detected by the qtdemux element, respectively. Once the audio and video streams are detected, the qtdemux element creates the video_%u and audio_%u pads and uses a callback function, cb_new_pad, to notify the downstream element, h264parser, that new pads are available. The cb_new_pad function is set as the callback for the “pad-added” signal on the qtdemux element, which means that the function is called every time a new pad is added to the element.</p><p>The cb_new_pad function takes the qtdemux element, the new pad, and the downstream element, h264parser, as its arguments. The function checks the name of the new pad and links it to the sink pad of the downstream element, h264parser, if it is the video_0 pad. If the link is successful, the function returns true, otherwise, it returns false. The %u in the video_%u and audio_%u pad name is a placeholder for a unique number, which means that every time a new video or audio pad is created, it will be given a unique number. For example, it can be video_0 or audio_0.</p><pre>void cb_new_pad (GstElement *qtdemux, GstPad* pad, gpointer data) {<br>  GstElement* h264parser = (GstElement*) data;<br>  gchar *name = gst_pad_get_name (pad);<br>  if (strcmp (name, &quot;video_0&quot;) == 0 &amp;&amp; <br>      !gst_element_link_pads(qtdemux, name, h264parser, &quot;sink&quot;)){<br>    g_printerr (&quot;Could not link %s pad of qtdemux to sink pad of h264parser&quot;, name);<br>  }<br>}</pre><p>The callback is added to the element using g_signal_connect.</p><pre>/* Link &quot;video_0&quot; pad of qtdemux to sink pad of h264Parse<br>* &quot;video_0&quot; pad of qtdemux is created only when <br>* a valid video stream is found in the input<br>* in that case only the pipeline will be linked */<br>g_signal_connect (qtdemux, &quot;pad-added&quot;, G_CALLBACK (cb_new_pad), h264parser);</pre><p>Similarly the sink_%u pad on the nvstreammux element is created on request, which means it is created as needed when it is required in the pipeline. This is done through the use of dynamic pads, which are pads that are created on demand based on the requirements of the pipeline.</p><p>In this specific pipeline, the nvstreammux element is used to multiplex the video stream with the metadata streams generated by other elements in the pipeline. When the nvv4l2decoder element pushes the data into the nvstreammux element, the nvstreammux element creates the sink_%u pad and connects it to the src pad of the upstream element, which is the nvv4l2decoder element. This allows the data to flow through the pipeline from the nvv4l2decoder element to the nvstreammux element.</p><p>The %u in the sink_%u pad name is a placeholder for the stream index that is being multiplexed, which means that every time a new sink pad is created, it will be given a unique number. For example, it can be sink_0 for stream 0 and so on.</p><pre>/* <br>* Dynamic linking<br>* sink_0 pad of nvstreammux is only created on request<br>* and hence cannot be linked automatically<br>* Need to request it to create it and then link it <br>* to the upstream element in the pipeline<br>*/<br>GstPad *sinkpad, *srcpad;<br>gchar pad_name_sink[16] = &quot;sink_0&quot;;<br>gchar pad_name_src[16] = &quot;src&quot;;<br><br>/* Dynamically created pad */<br>sinkpad = gst_element_get_request_pad (streammux, pad_name_sink);<br>if (!sinkpad) {<br>  g_printerr (&quot;Streammux request sink pad failed. Exiting.\n&quot;);<br>  return -1;<br>}<br><br>/* Statically created pad */<br>srcpad = gst_element_get_static_pad (nvv4l2decoder, pad_name_src);<br>if (!srcpad) {<br>  g_printerr (&quot;Decoder request src pad failed. Exiting.\n&quot;);<br>  return -1;<br>}<br><br>/* Linking the pads */<br>if (gst_pad_link (srcpad, sinkpad) != GST_PAD_LINK_OK) {<br>  g_printerr (&quot;Failed to link decoder to stream muxer. Exiting.\n&quot;);<br>  return -1;<br>}<br><br>/* Unreference the object */<br>gst_object_unref (sinkpad);<br>gst_object_unref (srcpad);</pre><p>qtdemux and h264parse will be linked in cb_new_pad . We also linked nvv4l2decoder and streammux by using the request pads. Now we are ready to link the rest of the elements.</p><pre>/* <br>* we link the elements together<br>* file-source -&gt; qtdemux -&gt; h264-parser -&gt; nvh264-decoder -&gt;<br>* nvinfer -&gt; tracker -&gt; nvvidconv -&gt; nvosd -&gt; nvvidconv2 -&gt; <br>* nvh264-encoder -&gt; qtmux -&gt; filesink */<br>if (!gst_element_link_many (source, qtdemux, NULL)) {<br>  g_printerr (&quot;Source and QTDemux could not be linked: 1. Exiting.\n&quot;);<br>  return -1;<br>}<br><br>if (!gst_element_link_many (h264parser, nvv4l2decoder, NULL)) {<br>  g_printerr (&quot;H264Parse and NvV4l2-Decoder could not be linked: 2. Exiting.\n&quot;);<br>  return -1;<br>}<br><br>if (!gst_element_link_many (streammux, pgie, tracker, nvvidconv, nvosd, nvvidconv2, nvv4l2h264enc, h264parser2, qtmux, sink, NULL)) {<br>  g_printerr (&quot;Rest of the pipeline elements could not be linked: 3. Exiting.\n&quot;);<br>  return -1;<br>}</pre><p>We are ready to start playing the pipeline!</p><pre>/* Set the pipeline to &quot;playing&quot; state */<br>g_print (&quot;Using file: %s\n&quot;, argv[1]);<br>gst_element_set_state (pipeline, GST_STATE_PLAYING);<br><br>/* Wait till pipeline encounters an error or EOS */<br>g_print (&quot;Running...\n&quot;);<br>g_main_loop_run (loop);</pre><p>Wait for the pipeline to finish and clean up!</p><pre>/* Out of the main loop, clean up nicely */<br>g_print (&quot;Returned, stopping playback\n&quot;);<br>gst_element_set_state (pipeline, GST_STATE_NULL);<br>g_print (&quot;Deleting pipeline\n&quot;);<br>gst_object_unref (GST_OBJECT (pipeline));<br>g_source_remove (bus_watch_id);<br>g_main_loop_unref (loop)</pre><p>In order to compile and run the code, you’ll need to create this Makefile</p><pre><br># Set appropriate CUDA Version here <br># Use command `nvcc --version` to check your default CUDA version<br>CUDA_VER:=11.6<br><br>APP:= deepstream_tutorial_app1<br><br>TARGET_DEVICE = $(shell gcc -dumpmachine | cut -f1 -d -)<br><br>LIB_INSTALL_DIR?=/opt/nvidia/deepstream/deepstream/lib/<br>APP_INSTALL_DIR?=/opt/nvidia/deepstream/deepstream/bin/<br><br>ifeq ($(TARGET_DEVICE),aarch64)<br>  CFLAGS:= -DPLATFORM_TEGRA<br>endif<br><br>SRCS:= $(wildcard *.c)<br><br>INCS:= $(wildcard *.h)<br><br>PKGS:= gstreamer-1.0<br><br>OBJS:= $(SRCS:.c=.o)<br><br>CFLAGS+= -I /opt/nvidia/deepstream/deepstream/sources/includes \<br>  -I /usr/local/cuda-$(CUDA_VER)/include<br><br>CFLAGS+= $(shell pkg-config --cflags $(PKGS))<br><br>LIBS:= $(shell pkg-config --libs $(PKGS))<br><br>LIBS+= -L/usr/local/cuda-$(CUDA_VER)/lib64/ -lcudart \<br>  -L$(LIB_INSTALL_DIR) -lnvdsgst_meta -lnvds_meta -lnvds_yml_parser \<br>  -lcuda -Wl,-rpath,$(LIB_INSTALL_DIR) \<br><br>all: $(APP)<br><br>%.o: %.c $(INCS) Makefile<br> $(CC) -c -o $@ $(CFLAGS) $&lt;<br><br>$(APP): $(OBJS) Makefile<br> $(CC) -o $(APP) $(OBJS) $(LIBS)<br><br>install: $(APP)<br> cp -rv $(APP) $(APP_INSTALL_DIR)<br><br>clean:<br> rm -rf $(OBJS) $(APP)</pre><p>In order compile you need to set proper CUDA_VER in the Makefile and use this command.</p><pre>make</pre><p>To run the program use the executable deepstream_tutorial_app1 provide absolute path to any mp4 file. I’ve used one of the sample streams from DeepStream for this purpose.</p><pre>./deepstream_tutorial_app1 /opt/nvidia/deepstream/deepstream/samples/streams/sample_720p.mp4</pre><p>After execution there should be an output.mp4 file created in the same directory. Here’s the output that was generated.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCTQa79HiUng%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCTQa79HiUng&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCTQa79HiUng%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/eabcba571363966fb2789309a55e7b32/href">https://medium.com/media/eabcba571363966fb2789309a55e7b32/href</a></iframe><h3>Bonus Section!</h3><p>What if I told you, that you could have skipped the whole section above and created the pipeline using just one big cli command? I know, you’d kill me for it, but the reason for writing all this code was to introduce some important concepts in GStreamer like elements, pads, linking (dynamic and static) setting state of the pipeline etc. But all of this can be done with a cli command, as long as you’re not doing something very complicated in which case you’ll be required to write the pipeline in C. Without further ado here’s the gst-launch command for creating the same GStreamer pipeline.</p><pre>gst-launch-1.0 filesrc location=/opt/nvidia/deepstream/deepstream/samples/streams/sample_720p.mp4 \<br>! qtdemux ! h264parse ! nvv4l2decoder ! m.sink_0 nvstreammux name=m batch-size=1 width=1920 height=1080 \<br>! nvinfer config-file-path=/opt/nvidia/deepstream/deepstream/sources/apps/sample_apps/deepstream-test1/dstest1_pgie_config.txt \<br>! nvtracker ll-lib-file=/opt/nvidia/deepstream/deepstream/lib/libnvds_nvmultiobjecttracker.so \<br>! nvvideoconvert ! nvdsosd ! nvvideoconvert ! nvv4l2h264enc ! h264parse ! qtmux ! filesink location=output.mp4</pre><p>Well folks, that’s all for this tutorial! You’ve learned how to set up a pipeline using Gstreamer elements and link them together. You’ve also learned how to link dynamically created pads. But wait, don’t go anywhere just yet! We’ve only just scratched the surface of what DeepStream can do. In the next tutorial, we’ll be diving deep(stream) into the world of probes and how to attach them to your pipeline. So, hold on to your horses and get ready for some serious pipeline shenanigans. See you in the next tutorial!</p><h3><strong>References</strong></h3><ul><li><a href="https://chirag4798.medium.com/nvidia-deepstream-101-a-beginners-guide-to-real-time-computer-vision-afefcb5d7fba">DeepStream101: Introduction and Setup to DeepStream</a></li><li><a href="https://docs.nvidia.com/metropolis/deepstream/dev-guide/text/DS_C_Sample_Apps.html#c-c-sample-apps-source-details">DeepStream Sample Applications</a></li><li><a href="https://gstreamer.freedesktop.org/documentation/tutorials/index.html?gi-language=c">GStreamer tutorials</a></li><li><a href="https://github.com/chirag4798/DeepStream101/">Sample Code on Github</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68148753cf96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nvidia DeepStream 101: A beginner’s guide to real-time computer vision]]></title>
            <link>https://chirag4798.medium.com/nvidia-deepstream-101-a-beginners-guide-to-real-time-computer-vision-afefcb5d7fba?source=rss-d2c48d19b103------2</link>
            <guid isPermaLink="false">https://medium.com/p/afefcb5d7fba</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deepstream]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Chirag Shetty]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 20:36:29 GMT</pubDate>
            <atom:updated>2023-01-11T10:43:35.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN2BvbWtm7yCIDdgO4aHrA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@opticonor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Conor Luddy</a> on <a href="https://unsplash.com/photos/IGa3Md8wP6g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this blog, we’re going to cover some seriously cool stuff:</p><ul><li>Introduction to DeepStream (because you can’t build something without knowing what it is)</li><li>Setting up DeepStream (because, let’s be real, it’s not going to set itself up) Buckle up, it’s going to be a wild ride!</li></ul><h3>Introduction to DeepStream</h3><p>Computer vision is a field of artificial intelligence that lets computers see and interpret the world around them. It’s used in all sorts of cool applications, like image and video analysis, object detection, and even making robots do our bidding. But the real reason we all love computer vision is for the real-time stuff. Who doesn’t love seeing things happen in (near) real-time? That’s where DeepStream comes in. It’s an SDK for building real-time computer vision applications on Nvidia GPUs and Jetson devices. It’s a framework for constructing GStreamer pipelines that can process video streams like a boss, and it’s loaded with pre-built plugins for tasks like object detection and tracking. And if you’re feeling adventurous, you can even make your own plugins! DeepStream can handle all sorts of video streams, from local files to network streams like RTSP. It also has hardware-accelerated support for video encoding and decoding, so you can process high-res streams easily. Plus, it integrates with TensorRT, a library for optimizing deep learning models for inference on Nvidia hardware. With all that power, you can run advanced computer vision models in real-time without breaking a sweat (or your computer). Long live computer vision!</p><h3>Setting up DeepStream-6.1</h3><p>Setting up DeepStream requires a lot of things, but the most important one is probably CUDA. If you’re brave enough to tackle the installation of CUDA, you deserve a medal (or at least a round of applause). Just be warned: CUDA and its dependant software can be a bit finicky when it comes to version mismatches. But don’t worry, this blog is here to help beginners get started with DeepStream without getting lost in Nvidia’s vast documentation (or tearing their hair out). The goal is to make your journey as smooth as possible, so don’t give up just yet!</p><p>The instructions for installing DeepStream is slightly different for dGPU (discrete GPU) devices and Jetson devices. In this blog, the instructions given are for setting up DeepStream on dGPU devices, specifically for Ubuntu machines. For Jetson or RHEL (Red Hat Enterprise Linux) devices follow the official documentation from <a href="https://docs.nvidia.com/metropolis/deepstream/dev-guide/text/DS_Quickstart.html#jetson-setup">Nvidia DeepStream SDK</a>.</p><p>Pre-requisites:</p><ul><li>GStreamer 1.16.2</li><li>NVIDIA driver 515.65.01</li><li>CUDA 11.7 Update 1</li><li>TensorRT 8.4.1.5</li></ul><p>Step1: Install GStreamer and other dependencies.</p><pre>sudo apt install \<br>libssl1.1 \<br>libgstreamer1.0-0 \<br>gstreamer1.0-tools \<br>gstreamer1.0-plugins-good \<br>gstreamer1.0-plugins-bad \<br>gstreamer1.0-plugins-ugly \<br>gstreamer1.0-libav \<br>libgstreamer-plugins-base1.0-dev \<br>libgstrtspserver-1.0-0 libjansson4 \<br>libyaml-cpp-dev gcc make git python3</pre><p>Step2: Install CUDA Toolkit and NVIDIA driver.</p><pre>wget https://developer.download.nvidia.com/compute/cuda/11.7.1/local_installers/cuda-repo-debian11-11-7-local_11.7.1-515.65.01-1_amd64.deb<br>sudo dpkg -i cuda-repo-debian11-11-7-local_11.7.1-515.65.01-1_amd64.deb<br>sudo rm /etc/apt/sources.list.d/*cuda*<br>sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/3bf863cc.pub<br>sudo add-apt-repository &quot;deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /&quot;<br>sudo apt-get update<br>sudo apt-get -y install cuda</pre><p>Step3: Install TensorRT</p><pre>$ sudo apt-get install libnvinfer8=8.4.1-1+cuda11.6 libnvinfer-plugin8=8.4.1-1+cuda11.6 libnvparsers8=8.4.1-1+cuda11.6 \<br>  libnvonnxparsers8=8.4.1-1+cuda11.6 libnvinfer-bin=8.4.1-1+cuda11.6 libnvinfer-dev=8.4.1-1+cuda11.6 \<br>  libnvinfer-plugin-dev=8.4.1-1+cuda11.6 libnvparsers-dev=8.4.1-1+cuda11.6 libnvonnxparsers-dev=8.4.1-1+cuda11.6 \<br>  libnvinfer-samples=8.4.1-1+cuda11.6 libcudnn8=8.4.1.50-1+cuda11.6 libcudnn8-dev=8.4.1.50-1+cuda11.6 \<br>  python3-libnvinfer=8.4.1-1+cuda11.6 python3-libnvinfer-dev=8.4.1-1+cuda11.6</pre><p>Step4: Install DeepStream (Using the .deb file)</p><pre>wget https://developer.nvidia.com/deepstream-6.1_6.1.1-1_amd64.deb<br>sudo apt-get install ./deepstream-6.1_6.1.1-1_amd64.deb</pre><p>Step5: Verify if DeepStream was installed successfully</p><pre>deepstream-app --version</pre><p>The output of the following command should show the respective version of DeepStream that was installed. Ignore the warnings related to the .so files missing for triton server.</p><h3><strong>Alternate Setup using Docker</strong></h3><p>DeepStream has got you covered with Docker containers for both dGPU and Jetson platforms. Deploying DeepStream applications has never been easier — just bundle all your dependencies into a container and you’re good to go. And where can you find these handy containers? Look no further than the NVIDIA container registry at <a href="https://ngc.nvidia.com/">https://ngc.nvidia.com</a>. Just grab the nvidia-docker package and you’ll have access to GPU resources from within your containers. It’s like magic (but with less waving of wands and more typing on a keyboard). Happy containerizing!</p><p>Pull the samples docker image to run sample applications using Docker</p><pre>docker pull nvcr.io/nvidia/deepstream:6.1.1-samples</pre><p>To run the docker container use the following command</p><pre>docker run -itd --rm --net=host --name deepstream --runtime nvidia -w /opt/nvidia/deepstream/deepstream nvcr.io/nvidia/deepstream:6.1.1-samples</pre><p>To run applications inside the docker container, use the following command</p><pre>docker exec -it deepstream bash<br>deepstream-app --version</pre><p>This will open a bash terminal inside the docker container which can be used to run any sample DeepStream application.</p><p>And that’s a wrap! You’re all set to start building DeepStream applications. In the <a href="https://medium.com/@chirag4798/nvidia-deepstream-101-a-step-by-step-guide-to-creating-your-first-deepstream-application-68148753cf96">next tutorial</a>, we’ll show you how to build a simple DeepStream application. No sweat, right? (Well, maybe a little sweat, but we’ll be there to help you every step of the way).</p><h3><strong>References</strong></h3><ul><li><a href="https://docs.nvidia.com/metropolis/deepstream/dev-guide/index.html">DeepStream Official Documentation</a></li><li><a href="https://gstreamer.freedesktop.org/documentation/tutorials/index.html?gi-language=c">GStreamer Tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afefcb5d7fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>