<?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 Ayush Raj on Medium]]></title>
        <description><![CDATA[Stories by Ayush Raj on Medium]]></description>
        <link>https://medium.com/@ayushraj2349?source=rss-1b2a4d792fb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3Bnad7Fw883DAuyyTJbHdQ.jpeg</url>
            <title>Stories by Ayush Raj on Medium</title>
            <link>https://medium.com/@ayushraj2349?source=rss-1b2a4d792fb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:19:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayushraj2349/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[The Final Chapter: Visualizing Predictions and Analyzing the Results]]></title>
            <link>https://medium.com/@ayushraj2349/the-final-chapter-visualizing-predictions-and-analyzing-the-results-17fd996e1104?source=rss-1b2a4d792fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/17fd996e1104</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Ayush Raj]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 22:49:28 GMT</pubDate>
            <atom:updated>2024-02-21T22:49:28.422Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Okay, so we’re heading towards the last part of our Project.</strong></blockquote><p><strong>This is the final Installment to wrap up our Object Detection Series. For optimal comprehension and seamless reading experience, following the series chronologically is advised. The structure is mapped here: </strong><a href="https://medium.com/@ayushraj2349/unveiling-the-world-of-object-detection-from-theory-to-real-world-applications-building-3cace88e658c"><strong>Series Introductory Blog.</strong></a></p><p>In this article, I’ll delving deep into the fascinating realm of visualizing predictions and analyzing the results of our first two groundbreaking projects. In this edition, we’ll shine a spotlight on the precision, recall, and mAP (mean Average Precision) metrics, offering valuable insights into the performance of both projects. Join us as we unveil the intricate details behind the scenes, exploring how these metrics quantify the accuracy and effectiveness of our object detection models. From visually inspecting predictions to conducting in-depth analyses, we’ll uncover the successes and challenges encountered along the way. Get ready for a data-driven exploration that promises to deepen your understanding of our projects and the exciting world of computer vision! Okay, So Let’s see them one by one:</p><h3>Project 1</h3><p>We’ve used pre-trained <strong>Faster R-CNN Model with Resnet50 backbone</strong> fine-tuned on this Dataset’s Train Split.</p><p>Then we evaluated the model on the test split. The Results are like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*28eF_wVua5BdY7WkGgh43w.png" /></figure><p>This is the Result obtained on a random image of the test dataset.</p><p><strong>Green &amp; Yellow Boxes represent the actual &amp; predicted boxes respectively.</strong></p><p>As you can already see, Predictions are quite good. Although, there are some redundant boxes on both the sides of the Image. But, that it is okay, after all you can’t expect to be 100% correct. And that is synonymous to life, isn’t it? Everything can’t be perfect. Sorry for taking a small detour to Philosophy, Haha. :) Coming back to point, what matters most is that the remaining boxes should have a high IoU with the corresponding ground truth boxes.</p><h3>Project 2</h3><p>We’ve used the SOTA Model <strong>YOLOv8 (Medium Version</strong>) fine-tuned on the same dataset.</p><p>And the Results &amp; the speed of inference were quite Promising. Have a look :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*6JqNtRqe0qmscfMVqSwF2w.png" /></figure><p>Results obtained on an image of the Test Dataset.</p><p>Here, Not only the model was able to predict helmet class accurately with good confidence, it was able to predict head class well. Again, some redundant boxes. The output numbers are confidence scores for the classes mentioned nearby.</p><h3><strong>Comparing the two Models</strong></h3><p>For evaluating the performance of both the models, we turn to key metrics such as precision, recall, and mean Average Precision (mAP). <strong>Precision measures the accuracy of our model’s predictions by assessing the proportion of true positive detections among all positive predictions</strong>. On the other hand, <strong>recall evaluates the model’s ability to correctly identify all relevant instances, capturing the proportion of true positive detections among all actual positive instances</strong>. These metrics provide valuable insights into the trade-off between precision and recall, allowing us to fine-tune our models for optimal performance.</p><p>Furthermore, <strong>mean Average Precision (mAP) offers a comprehensive assessment of our model’s overall accuracy across different object classes.</strong> By averaging the precision-recall curves for each class and calculating the area under the curve (AUC), mAP provides a single numerical value that summarizes the model’s performance across the entire dataset. This metric serves as a powerful tool for comparing the effectiveness of different models and tracking improvements over time.</p><p>By analyzing these metrics, we gain valuable insights into the strengths and weaknesses of our models, enabling us to make informed decisions for future enhancements and optimizations</p><blockquote><strong><em>Evaluation on Precision and Recall Metrics</em></strong></blockquote><blockquote><strong><em>Just to reiterate, we’ve used YOLOv8 Medium version everywhere (yolov8m).</em></strong></blockquote><p>Here, we’ll present the results that we got during our evaluation.</p><p>We’ve calculated the Precision and Recall per class for all the 3 classes, but the point of interest since the beginning, is our Helmet Class. So, I’ve showed only that Class. Have a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*IIFwf6b6TyvhVUnz6mttkg.png" /><figcaption>Image by Author</figcaption></figure><p>After examining the precision and recall values for both YOLO and Faster R-CNN, it’s evident that there is a significant disparity in performance, particularly with Faster R-CNN exhibiting notably lower values. This discrepancy highlights potential shortcomings in the Faster R-CNN model’s ability to accurately detect objects compared to YOLO.</p><p><strong>Possible reasons for the lower precision and recall values with Faster R-CNN could include issues such as:</strong></p><ol><li><strong>Difficulty in capturing intricate object details:</strong> Faster R-CNN may struggle to accurately detect objects with complex shapes or textures, leading to missed detections or false positives.</li><li><strong>Insufficient training data: </strong>The Faster R-CNN model may not have been adequately trained on diverse and representative datasets, limiting its ability to generalize to new or unseen scenarios. And this you already knew, because as mentioned earlier, our dataset was heavily imbalanced.</li><li><strong>Suboptimal model architecture:</strong> The design and configuration of the Faster R-CNN model architecture may not be optimized for the specific object detection task at hand, resulting in subpar performance compared to YOLO.</li></ol><p>Moving forward, it may be beneficial to explore strategies for improving the performance of the Faster R-CNN model, such as fine-tuning model hyperparameters, augmenting training data, or considering alternative model architectures. By addressing these challenges, we can work towards achieving higher precision and recall values, ultimately enhancing the overall effectiveness of our object detection systems using Faster R-CNN.</p><blockquote><strong><em>Evaluation on Mean Average Precision(mAP) at an IoU Threshold of 0.5.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*EervUgF0i3nGcpVC8wAmrQ.png" /><figcaption>Image by Author</figcaption></figure><p>Upon examining the mean Average Precision (mAP) values at an Intersection over Union (IoU) threshold of 0.5 for both YOLO and Faster R-CNN, it’s notable that the performance of the Faster R-CNN model appears to be reasonably decent. <strong>However, the YOLO model demonstrates significantly superior performance in comparison</strong>.</p><p>While the Faster R-CNN model exhibits a seemingly decent mAP score, it’s evident that the YOLO model outperforms it by a considerable margin. This observation underscores the effectiveness and efficiency of the YOLO approach in object detection tasks, highlighting its potential to deliver more accurate and reliable results across diverse datasets and scenarios.</p><p>The values of the two models emphasizes the need for careful consideration when selecting an object detection approach. <strong>Factors such as model complexity, computational efficiency, and task-specific requirements should be taken into account to ensure optimal performance and effectiveness in real-world applications.</strong></p><blockquote><strong><em>FPS (Frames per Second)</em></strong></blockquote><p>Frames per second (FPS) serve as a crucial measure of a model’s real-time performance, directly impacting its usability in dynamic environments. Achieving high FPS rates signifies the model’s ability to process video streams swiftly, facilitating timely decision-making and enhancing overall efficiency. Monitoring and optimizing FPS is essential for ensuring seamless integration of object detection systems into applications such as surveillance, autonomous vehicles, and augmented reality, where real-time responsiveness is paramount. It is calculated mathematically as 1/the time taken by a single frame(image) from pre-processing, inference to post-processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*CmhkeQVMyZjyW1oGxrhBOA.png" /><figcaption>Image by Author</figcaption></figure><p>YOLO, due to its rapid processing speed, took only <strong>12ms</strong> on an avg. for a single frame in our Test Datasets and Video Files. So, the FPS comes out to be 1000/12 i.e. <strong>83 FPS.</strong></p><p>While Faster R-CNN for the same task took 142ms on avg. So, the FPS comes out to be 1000/14 i.e. <strong>7 FPS, </strong>which is very low, making it unfit for Real-Time Object Detection Tasks<strong>.</strong></p><blockquote><strong>Note: Keep in mind that FPS can vary based on factors like input resolution, system load, and specific hardware capabilities.</strong></blockquote><p>Here we’ve calculated this using “Tensor 4” GPU</p><h3>Conclusion</h3><ul><li><strong>The YOLO model consistently demonstrates superior FPS rates, Precision and Recall Values over</strong>.</li><li><strong>While the Faster R-CNN model may offer relatively decent performance in terms of precision and recall, but it lags behind YOLO.</strong></li><li><strong>The significant difference in frames per second (FPS) between Faster R-CNN (7 FPS) and YOLO (83 FPS) is critical in the context of real-time object detection. For any model to be able to run on Video Files, it must have a minimum of 24 fps as this is the standard for videos.</strong></li></ul><p>With a higher FPS, YOLO demonstrates a remarkable ability to process video streams swiftly, facilitating real-time object detection in dynamic environments. <strong>This rapid processing capability is particularly advantageous in applications such as surveillance, autonomous vehicles, and augmented reality, where timely decision-making is essential.</strong></p><p>In contrast, the lower FPS of Faster R-CNN may limit its suitability for real-time scenarios, potentially causing delays in detection and response. Therefore, the superior FPS of YOLO positions it as a more viable solution for applications requiring efficient and responsive object detection in real-time.</p><p>So, yeah! Now, we’ve successfully covered all the concepts required for Object Detection in particular for this Project and obviously their implementation in the Project itself!</p><h3><strong>Our Learning Experience</strong></h3><p>Throughout this project journey, we’ve embarked on a transformative learning experience that has enriched our understanding of object detection and deepened our expertise in computer vision. From grappling with complex algorithms to navigating the nuances of model implementation, every step has been a testament to perseverance and growth. We’ve embraced challenges as opportunities for learning, honing our problem-solving skills and expanding our technical repertoire. Moreover, collaborating with peers and mentors has fostered a sense of community and shared knowledge, fueling our passion for innovation and discovery. As we reflect on this journey, we emerge with newfound insights, ready to apply them to future endeavors and continue our pursuit of excellence in the field of AI.</p><h3><strong>Wrapping Up!</strong></h3><p>Yeah, now we end this series of blogs where we’ve meticulously explored every aspect of our projects, from understanding the fundamentals to delving into the intricacies of implementation. With concepts clarified and implementations dissected, we’ve embarked on a journey of discovery, uncovering insights and pushing boundaries in the realm of object detection. <strong>As the curtain falls on this series, we stand poised at the intersection of theory and practice, armed with newfound knowledge and ready to tackle the challenges that lie ahead in the ever-evolving field of Computer Vision.</strong></p><blockquote><strong><em>We’re thrilled to have shared our journey with Object Detection, especially its application in Real-World Problems. If you’re interested in learning more about our project or have any queries regarding the topics or anything in general, feel free to reach out! We’ll be giving our emails at the end.</em></strong></blockquote><blockquote><strong><em>This Blog Series is a product of our dedicated teamwork. We strive for accuracy, but mistakes can happen. If you notice any errors or typos, please point them out and let us know in the comments below.</em></strong></blockquote><p>If this Series helped, we’ll be very happy to know that! I also invite you to reflect on your own experiences and insights gained from our exploration on Object Detection. Consider how these insights might influence your approach to future projects or spark new ideas for applications. Feel free to share any challenges you faced or breakthroughs you experienced while working with this technology. Your contributions to our collective understanding are invaluable, and we look forward to hearing from you. Thank you for being part of our learning journey on Object Detection!</p><p>Till then, Goodbye and Happy Learning! :)</p><p><strong>Do Follow for more such content!!!</strong></p><ul><li><a href="https://medium.com/subscribe/@ayushraj2349?source=publishing_settings---user_settings----------------------------------">Get an email whenever Ayush Raj publishes.</a></li><li><a href="https://medium.com/subscribe/@vkt08?source=publishing_settings---user_settings----------------------------------">Get an email whenever Vikash Kumar Thakur publishes.</a></li></ul><h3>About the Authors</h3><p><a href="https://medium.com/@ayushraj2349">Ayush Raj</a> — <a href="http://ayushraj2349@gmail.com/">Reach out to me!</a></p><p><a href="https://medium.com/@vkt08">Vikash Kumar Thakur</a> — <a href="http://vkthakur082002@gmail.com/">Reach out to me!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17fd996e1104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Faster R-CNN and YOLOv8 for the Helmet Detection Project: The Coding Aspect]]></title>
            <link>https://medium.com/@ayushraj2349/implementing-faster-r-cnn-and-yolov8-for-the-helmet-detection-project-the-coding-aspect-8f548ff193c5?source=rss-1b2a4d792fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f548ff193c5</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ayush Raj]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 21:53:06 GMT</pubDate>
            <atom:updated>2024-02-21T21:53:06.363Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>This is the 5th Installment of the Series. To catch up, you can always go back and refer to: </strong><a href="https://medium.com/@ayushraj2349/unveiling-the-world-of-object-detection-from-theory-to-real-world-applications-building-3cace88e658c"><strong>Series Introductory Blog.</strong></a></blockquote><h3><strong>Dataset used during the Whole Project</strong></h3><p>For the Dataset, we used one of the datasets publicly available on the Kaggle Website. Here’s the link:</p><p><a href="https://www.kaggle.com/datasets/andrewmvd/hard-hat-detection">Safety Helmet Detection</a></p><p>This dataset, contains 5000 images with bounding box annotations in the PASCAL VOC format (x_min, y_min, x_max, y_max) for these 3 classes:</p><p>They’re [helmet, head &amp; person], but mainly to predict helmet because the data is heavily imbalanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJEp3wrHnsDEq2PHFwEP_Q.jpeg" /><figcaption>This picture demonstrates the imbalance in the dataset among the classes — Image by Author</figcaption></figure><p><strong>As you can clearly see from the histogram plotted above, almost 75% of the occurrences in the Dataset is of helmet class which is a not good thing.</strong></p><p>Although, this dataset was never our first choice, but this was the only decent one we could found on the Internet.</p><p>And this will also work because our main purpose is to detect helmets, for which there are sufficient data samples. I can suggest you some measures to fix this issue, if you want. This dataset is not properly sampled. So, you can use some the re-sampling techniques, primarily Undersampling and Oversampling. But Undersampling must not be used here as this is not what you’ll want. You’ll not prefer the occurrences of Helmet to be low. Remember more the data samples, the better the Results!</p><p>Additionally, there are more advanced resampling techniques, such as SMOTE (Synthetic Minority Over-sampling Technique), ADASYN (Adaptive Synthetic Sampling), and others, which generate synthetic samples for the minority class based on their nearest neighbors. These methods aim to create more diverse and representative synthetic samples compared to simple duplication.</p><p><strong>We’ve Partitioned the whole Dataset into Train, Val &amp; Test Sets in the proportion of 8:1:1 for all our Projects. This will be 4000, 500 and 500 images for the mentioned sets above respectively.</strong></p><p>So, Let’s Jump into the Projects right away! The Section you all were waiting for, since we started this Object Detection Blog Series.</p><blockquote><strong><em>We’ve implemented all Projects using </em></strong><a href="https://pytorch.org/"><strong><em>PyTorch</em></strong></a><strong><em> Framework.</em></strong></blockquote><h3>Project 1</h3><p><em>We’ve used a pre-trained</em><strong> Faster R-CNN Model with Resnet50<em> </em>backbone<em> </em></strong><em>fine-tuned on this Dataset’s Train Split.</em></p><p>Let’s See the Code Snippets for Training The Model:</p><pre>#### Function Defn for Training Iterations<br><br><br><br># function for running training iterations<br>from tqdm import tqdm<br><br>def train(train_data_loader, model):<br>    print(&#39;Training...&#39;)<br>    global train_itr<br>    global train_loss_list<br><br>    # initialize tqdm progress bar<br>    prog_bar = tqdm(train_data_loader, total=len(train_data_loader))<br><br>    # criterion = torch.nn.BCELoss(size_average=True)<br><br>    for i, data in enumerate(prog_bar):<br>        optimizer.zero_grad() #####<br>        images, targets = data #####<br><br>        images = list(image.to(DEVICE) for image in images) #####<br>        targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets] #####<br><br>        loss_dict = model(images, targets) #####<br>        losses = sum(loss for loss in loss_dict.values()) #####<br>        loss_value = losses.item()<br>        train_loss_list.append(loss_value)<br>        train_loss_hist.send(loss_value)<br>        losses.backward() #####<br>        optimizer.step() #####<br>        train_itr += 1 #####<br><br>        # update the loss value beside the progress bar for each iteration<br>        prog_bar.set_description(desc=f&quot;Loss: {loss_value:.4f}&quot;)<br>    return train_loss_list</pre><pre>##### Function Defn for Validation Iterations<br><br><br><br># The validation function returns a similar list containing the loss values<br># for all the completed iterations<br><br># function for running validation iterations<br>def validate(valid_data_loader, model):<br>    print(&#39;Validating...&#39;)<br>    global val_itr<br>    global val_loss_list<br><br>    # initialize tqdm progress bar<br>    prog_bar = tqdm(valid_data_loader, total=len(valid_data_loader))<br><br>    for i, data in enumerate(prog_bar):<br>        images, targets = data<br><br>        images = list(image.to(DEVICE) for image in images)<br>        targets = [{k: v.to(DEVICE) for k, v in t.items()} for t in targets]<br><br>        with torch.no_grad():<br>            loss_dict = model(images, targets)<br>        losses = sum(loss for loss in loss_dict.values())<br>        loss_value = losses.item()<br>        val_loss_list.append(loss_value)<br>        val_loss_hist.send(loss_value)<br>        val_itr += 1<br><br>        # update the loss value beside the progress bar for each iteration<br>        prog_bar.set_description(desc=f&quot;Loss: {loss_value:.4f}&quot;)<br>    return val_loss_list</pre><pre>#### Averager Class for loggging Training &amp; Validation Losses.<br>#### Then we save model for the best epoch we&#39;ll get as we progress.<br>#    We save this bcoz this is the one on which we&#39;ll evaluate<br>#    Our Test Set for Results. Obviously, you want the model which has<br>#    the best minimum loss.<br>#### We also save the Last Model to have a backup in case of<br>#    in case of unexpected interruptions or errors during training,<br>#    ensuring that we don&#39;t lose valuable progress.<br><br>class Averager:<br>    def __init__(self):<br>        self.current_total = 0.0<br>        self.iterations = 0.0<br><br>    def send(self, value):<br>        self.current_total += value<br>        self.iterations += 1<br><br>    @property<br>    def value(self):<br>        if self.iterations == 0:<br>            return 0<br>        else:<br>            return 1.0 * self.current_total / self.iterations<br><br>    def reset(self):<br>        self.current_total = 0.0<br>        self.iterations = 0.0<br><br>class SaveBestModel:<br>    &quot;&quot;&quot;<br>    Class to save the best model while training. If the current epoch&#39;s<br>    validation loss is less than the previous least less, then save the<br>    model state.<br>    &quot;&quot;&quot;<br>    def __init__(self, best_valid_loss=float(&#39;inf&#39;)):<br>        self.best_valid_loss = best_valid_loss<br><br>    def __call__(self, current_valid_loss, epoch, model, optimizer):<br>        if current_valid_loss &lt; self.best_valid_loss:<br>            self.best_valid_loss = current_valid_loss<br>            print(f&quot;\nBest validation loss: {self.best_valid_loss:.3f}&quot;)<br>            print(f&quot;\nSaving best model for epoch: {epoch+1}\n&quot;)<br>            torch.save({<br>                &#39;epoch&#39;: epoch+1,<br>                &#39;model_state_dict&#39;: model.state_dict(),<br>                &#39;optimizer_state_dict&#39;: optimizer.state_dict(),<br>                &#39;scheduler_state_dict&#39;: scheduler.state_dict(),<br>                }, &#39;/content/drive/My Drive/helmet_dataset/savedmodel/best_model.pth&#39;)<br><br><br># function to save the model after each epoch and after training ends<br>def save_model(epoch, model, optimizer):<br>    &quot;&quot;&quot;<br>    Function to save the trained model till current epoch, or whenver called<br>    &quot;&quot;&quot;<br>    torch.save({<br>                &#39;epoch&#39;: epoch+1,<br>                &#39;model_state_dict&#39;: model.state_dict(),<br>                &#39;optimizer_state_dict&#39;: optimizer.state_dict(),<br>                &#39;scheduler_state_dict&#39;: scheduler.state_dict(),<br>                }, &#39;/content/drive/My Drive/helmet_dataset/savedmodel/last_model.pth&#39;)</pre><pre># The Training Loop<br><br># initialize the Averager class<br>train_loss_hist = Averager()<br>val_loss_hist = Averager()<br>train_itr = 1<br>val_itr = 1<br><br># train and validation loss lists to store loss values of all<br># iterations till end and plot graphs for all iterations<br>train_loss_list = []<br>val_loss_list = []<br><br># initialize SaveBestModel class<br>save_best_model = SaveBestModel()<br><br>NUM_EPOCHS = 16 # number of epochs to train for<br>epoch=0<br><br># start the training epochs<br>for epoch in range(epoch, NUM_EPOCHS):<br>    print(f&quot;\nEPOCH {epoch+1} of {NUM_EPOCHS}&quot;)<br><br>    # reset the training and validation loss histories for the current epoch<br>    train_loss_hist.reset()<br>    val_loss_hist.reset()<br><br>    train_loss = train(train_loader, model)<br>    val_loss = validate(valid_loader, model)<br><br>    print(scheduler.get_last_lr()) # this prints the lr used in training that specific epoch<br>    scheduler.step()<br><br>    print(f&quot;Epoch #{epoch+1} train loss: {train_loss_hist.value:.3f}&quot;)<br>    print(f&quot;Epoch #{epoch+1} validation loss: {val_loss_hist.value:.3f}&quot;)<br><br>    # save the best model till now if we have the least loss in the current epoch<br>    save_best_model(val_loss_hist.value, epoch, model, optimizer)<br>    # save the current epoch model<br>    save_model(epoch, model, optimizer)<br><br>    # save is done after scheduler.step(), as info<br>    # related to scheduler is saved in terms of steps, if saved before using scheduler.step(), it would cause training one more epoch<br>    # in a specific lr, here step size is 5, so when resumed training it will train one more epoch on that lr causing 6 to train using that<br>    # particular lr, which will be wrong.</pre><p>These Snippets will guide you through the whole training process used for this Project. Just to give you a brief outline, we first defined the functions for iterating through the Training &amp; Validation Datasets. Then we defined classes for logging losses and for saving the best and last Models. And then we have the final snippet for The Training Loop. <strong>Just look at the snippets once thoroughly. I’ve tried to explain each and every step in best possible way. Hope you get all of them!</strong></p><p>Hey, one more thing, you know na what these are and why they are used here? Just few Questions to check your understanding on how training of a deep neural network happens:</p><ol><li><strong><em>Why we need Validation set? Aren’t only training and testing sets enough?</em></strong></li><li>This is the follow-up question for 1st. <strong><em>What are overfitting and underfitting, and how can we mitigate them during training?</em></strong></li><li><strong><em>How does regularization, such as L1 and L2 regularization, help prevent overfitting? Which type of regularization we’ve used here?</em></strong></li><li><strong><em>How does gradient descent work, and what are the different variants of gradient descent optimization algorithms?</em></strong></li><li><strong><em>What are epochs and batch size, and how do they impact the training process?</em></strong></li><li><strong><em>How do learning rate and learning rate scheduling affect the convergence of the training process?</em></strong></li><li><strong><em>How to gain insights on what’s happening and why it is so, in the Training Process?</em></strong></li></ol><p>If you’re struggling with any of these questions, you need to re-visit the concepts again. Just google it, you’ll find some very good resources out there. I’ll also try to share some of them!</p><h3><strong>Challenges and Solutions during Implementation</strong></h3><p>I can’t tell you how challenging and painful it was! <strong>We experimented with the Training Process more than 25 times with different possible configurations to achieve best possible loss. </strong>And still we don’t think we’ve the best possible model with us. We had to change and try different things every time like tuning of hyperparameters, what should be the value of Learning Rate, value of weight decay, value of momentum, no. of epochs (will it underfit or overfit), which optimizer to use, should we incorporate momentum or not, should we train with or without learning rate scheduling, should we increase it or decrease the learning rate(will it overshoot)? If we do so, what will be the effect on validation loss? when to stop during training so that in next epoch, it shouldn’t start overfitting.</p><p>Wait, wait! Don’t get scared of this. These are challenging but this is also what makes the Neural Networks so powerful. This is Deep Learning, field of experimentation! You have to experiment again and again to achieve the desired outcome. But this becomes time-taking and challenging many of the times.</p><p>Now come to the Solutions Part. The Solution to these challenges is that there is no exact solution. Yes, I m not joking. There is no cast of stone to follow. It depends on the Problem at hand. <strong>But surely, there are some tips to ensure better Training of the Model. </strong>Let’s look at them:</p><h4>Tips for initial learning rate</h4><ol><li>Tune learning rate [Try different values on a log scale: 0.0001, 0.001, 0.01, 0.1, 1.0].</li><li>Run a few epochs with each of these and figure out a learning rate which works best.</li><li>Now do a finer search around this value [for example, if the best learning rate was 0.1 then now try some values around it: 0.05, 0.2, 0.3].</li><li>Disclaimer: these are just heuristics … no clear winner strategy.</li></ol><h4>Tips for annealing learning rate</h4><p><strong>Step Decay:</strong></p><ol><li>Halve the learning rate after every 5 epochs or</li><li>Halve the learning rate after an epoch if the validation error is more than what it was at the end of the previous epoch.</li></ol><h4>Tips for momentum</h4><p>The following schedule was suggested by Ilya Sutskever, Chief Scientist, OpenAI :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*4TegHsmSSnDlCo0KIpT3gg.png" /><figcaption>Formula for Momentum — By Ilya Sutskever</figcaption></figure><h4><strong>Million dollar question: Which algorithm to use in practice?</strong></h4><ol><li><strong>Adam seems to be more or less the default choice now ( beta1 = 0.9, beta2 = 0.999 and epsilon = 1e -8 ).</strong></li><li><strong>Having said that, many papers report that SGD with momentum (Nesterov or classical) with a simple annealing learning rate schedule also works well in practice (typically, starting with lr = 0.001, or 0.0001)</strong></li></ol><blockquote><strong>So, in conclusion (SGD + Momentum) or Adam with a scheduler might just be the best choice overall!!!</strong></blockquote><p><strong>So, finally, here’s the list of hyperparameter values which i used in this Project:</strong></p><h3>SGD with Momentum is used along with Step LR Scheduling.</h3><ol><li>SGD Hyperparameters</li></ol><ul><li>Learning Rate(η) = 0.001</li><li>Momentum (β) = 0.9</li><li>Weight Decay(λ) (L2 Regularization) = 0.0005</li></ul><p>2. Step LR Scheduling Hyperparameters</p><ul><li>Step Size = 4</li><li>Gamma (γ) = 0.5</li></ul><p>3. No. of Epochs = 16</p><p>4. Batch Size = 4</p><h3><strong>Project 2</strong></h3><p><em>We’ve used the State of the Art Model</em> <strong>YOLOv8 (Medium Version)</strong> <em>fine-tuned on the same dataset</em>.</p><p>See, in coding aspect, there’s nothing much for YOLO. Mostly everything is under the hood, because YOLO believes in no-code policy so that it becomes accessible for everyone.</p><p>We can implement YOLO using any of the two methods which are through CLI commands or Python Environment.</p><p>Generally, we use CLI commands for tasks like training &amp; making predictions which is the simplest task you can do with YOLO.</p><p>For complex tasks which are built on top of YOLOv8, like just to name a few Object Counting, Tracking or Speed Estimation of Vehicles and many more, it is generally advised to use Pythonic Version for minimizing performance &amp; bug issues. And that’s what our next Project is built for.</p><p>So, in this Project, we used CLI commands for simplicity and for keeping code look clean.</p><p>I’ll provide you some snippets for that:</p><pre>!git clone https://github.com/ultralytics/ultralytics<br>!pip install ultralytics</pre><pre># For example:<br><br># &quot;/content/drive/My Drive/helmet_dataset_YOLO/images/train/hard_hat_workers0.png&quot;  # image<br># &quot;/content/drive/My Drive/helmet_dataset_YOLO/labels/train/hard_hat_workers0.txt  # label<br><br>import yaml<br><br># Create configuration<br>config = {<br><br>   &quot;train&quot;: &quot;/content/drive/My Drive/helmet_dataset_YOLO/images/train&quot;,<br>   &quot;val&quot;: &quot;/content/drive/My Drive/helmet_dataset_YOLO/images/val&quot;,<br>   &quot;test&quot;: &quot;/content/drive/My Drive/helmet_dataset_YOLO/images/test&quot;,<br>   &quot;nc&quot;: 3,<br>   &quot;names&quot;: [&#39;helmet&#39;,&#39;head&#39;,&#39;person&#39;]<br>}<br>with open(&quot;data.yaml&quot;, &quot;w&quot;) as file:<br>   yaml.dump(config, file, default_flow_style=False)</pre><pre>!yolo task=detect mode=train data=data.yaml model=yolov8m.pt epochs=20 lr0=0.01</pre><p>For training the model, first you need to convert your data into YOLO format,(x_centre, y_centre, width, height) if not done so.</p><p>Then a .yaml file is needed for YOLO which stores all the paths for all your sets (train, val &amp; test) and the classes. This is the file that you’ll pass to the training command as argument.</p><p>Next, we have the Training command, Let’s break it one by one:</p><p><strong>TASK : </strong>YOLOv8 is an AI framework that supports multiple computer vision <strong>tasks</strong>. The framework can be used to perform <a href="https://docs.ultralytics.com/tasks/detect/">detection</a>, <a href="https://docs.ultralytics.com/tasks/segment/">segmentation</a>, <a href="https://docs.ultralytics.com/tasks/obb/">obb</a>, <a href="https://docs.ultralytics.com/tasks/classify/">classification</a>, and <a href="https://docs.ultralytics.com/tasks/pose/">pose</a> estimation. Each of these tasks has a different objective and use case. So, the task parameter can take values like <a href="https://docs.ultralytics.com/tasks/detect/">detect</a> for Object Detection, <a href="https://docs.ultralytics.com/tasks/segment/">segment</a> for Instance Segmentation, <a href="https://docs.ultralytics.com/tasks/obb/">obb</a> for Oriented Object Detection, <a href="https://docs.ultralytics.com/tasks/classify/">classification</a> for Image Classification, and <a href="https://docs.ultralytics.com/tasks/pose/">pose</a> for Pose Estimation. We’re using it for Object Detection. So, we’ll use detect for task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjHnMknWnvFxYw-ilCbR0Q.png" /></figure><p><strong>MODE :</strong></p><ul><li><strong>Train</strong> mode: Fine-tune your model on custom or preloaded datasets.</li><li><strong>Val</strong> mode: A post-training checkpoint to validate model performance.</li><li><strong>Predict</strong> mode: Unleash the predictive power of your model on real-world data.</li><li><strong>Export</strong> mode: Make your model deployment-ready in various formats.</li><li><strong>Track</strong> mode: Extend your object detection model into real-time tracking applications.</li><li><strong>Benchmark</strong> mode: Analyze the speed and accuracy of your model in diverse deployment environments.</li></ul><p>Data= data.yaml. Here we’re passing the .yaml file we made for to YOLO model to access required path.</p><p><strong>MODEL: </strong>As I’ve already explained you about the different model versions in my previous blog on YOLO, you know that there 5 different versions and we’re here using the medium which is a good trade-off between speed and accuracy for the Problem Statement we’ve have in our hand.</p><p>epochs and lr, as you already have understood denotes no. of epochs and learning rate respectively.</p><blockquote><strong>Till now, you must be wondering, where are the other things like optimizer, scheduler or batch size? There’s must be something fishy.</strong></blockquote><p>But there’s not! Actually what YOLO does is that it internally stores default values for all the configurations and hyperparameter values in as file named “<a href="https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml">default.yaml</a>”. So, if we don’t pass explicitly values of any configuration, it will take the default value. Like here we specified values for epochs and learning rate but that doesn’t mean that the default yaml files don’t have values for that. It’s just that we’re not not using the default values. Just check out the “<a href="https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml">default.yaml</a>” file once. You’ll get what i just explained.</p><p>Here’s the list of hyperparameter values we’ve used in this Project, in one-place, for a better reference.</p><h3>Training Hyperparameters</h3><ol><li><strong>Epoch = 20</strong></li><li><strong>Batch Size = 16</strong></li><li><strong>Workers = 8 (number of worker threads for data loading)</strong></li><li><strong>Initital Learning Rate (</strong>ηi<strong>) [lr0] = 0.01</strong></li><li><strong>Final Learning Rate (</strong>ηf<strong>) [lr0 * lrf] = 0.01 * 0.01 = 0.0001</strong></li><li><strong>Optimizer is set to auto, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto]</strong></li><li><strong>Momentum (β) = 0.937 (SGD momentum / Adam (</strong>β1<strong>) )</strong></li><li><strong>Weight Decay (λ) = 0.0005</strong></li><li><strong>Linear LR Scheduler which deacys η every epoch linearly from (</strong>ηi<strong>) to (</strong>ηf<strong>) at the last epoch of training.</strong></li></ol><p><strong>All hyperparameters &amp; configurations including the above are used with their (default values) except for number of epochs whose default value is 100.</strong></p><h3>Tips for best Training Results</h3><p>Most of the time good results can be obtained with no changes to the models or training settings. If at first you don’t get good results, there are steps you might be able to take to improve.</p><ol><li><strong>Epochs</strong> : Start with 300 epochs. If this overfits early then you can reduce epochs. If overfitting does not occur after 300 epochs, train longer, i.e. 600, 1200 etc. epochs.</li><li><strong>Image size</strong> : COCO trains at native resolution of — img 640, though due to the high amount of small objects in the dataset it can benefit from training at higher resolutions such as — img 1280. If there are many small objects then custom datasets will benefit from training at native or higher resolution. Best inference results are obtained at the same — img as the training was run at, i.e. if you train at — img 1280 you should also test and detect at — img 1280.</li><li><strong>Batch size</strong> : Use the largest batch size that your hardware allows for. Small batch sizes produce poor batchnorm statistics and should be avoided.</li></ol><h3>Hyperparameter Tuning</h3><p><strong>Ultralytics YOLO uses genetic algorithms to optimize hyperparameters. Genetic algorithms are inspired by the mechanism of natural selection and genetics.</strong></p><p><strong>Mutation</strong> : In the context of Ultralytics YOLO, mutation helps in locally searching the hyperparameter space by applying small, random changes to existing hyperparameters, producing new candidates for evaluation.</p><p><strong>Crossover</strong> : Although crossover is a popular genetic algorithm technique, it is not currently used in Ultralytics YOLO for hyperparameter tuning. The focus is mainly on mutation for generating new hyperparameter sets.</p><h3><strong>Project 3</strong></h3><p>As you know from the overview of the series, This Project is a tool that we’ve built on top of YOLO.</p><p><strong>This Tool is Object Counting in Real-Time Videos. </strong>Just to reiterate,</p><blockquote>This tool simply plots the bounding boxes of Helmets without confidence score (else it will become clumsy, just to look clean) and displays the current count of Helmets in the videos.</blockquote><p>And you already know the applications that I’ve mentioned in the Introductory Blog of this Series.</p><p>Regarding the Coding Part, there’s nothing much. But I’ll brief it once:</p><pre>!pip install ultralytics -q<br>import ultralytics<br>ultralytics.__version__</pre><pre>from ultralytics import YOLO<br><br>import time<br>import torch<br>import cv2<br>from PIL import Image<br>import numpy as np<br>import torch.backends.cudnn as cudnn<br># a module that provides access to functionality related to NVIDIA&#39;s CUDA Deep Neural Network library (cuDNN)<br># accelerates GPU Performance.</pre><pre>from ultralytics import YOLO<br>import cv2<br>import os<br>from tqdm import tqdm<br><br>model = YOLO(&quot;/content/drive/MyDrive/Object_Counting_YOLOv8/best.pt&quot;) # load a trained model fine-tuned on your custom dataset<br><br>class_names =[ &#39;helmet&#39;, &#39;head&#39;, &#39;person&#39;]    # the class objects<br><br>device = torch.device(&#39;cuda:0&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br><br># Define the video paths<br>video_paths = [&#39;/content/drive/MyDrive/Object_Counting_YOLOv8/videos/1.mp4&#39;,&#39;/content/drive/MyDrive/Object_Counting_YOLOv8/videos/2.mp4&#39;,<br>               &#39;/content/drive/MyDrive/Object_Counting_YOLOv8/videos/3.mp4&#39;,<br>               &#39;/content/drive/MyDrive/Object_Counting_YOLOv8/videos/4.mp4&#39;]<br><br>output_directory = &#39;/content/drive/MyDrive/Object_Counting_YOLOv8/output_videos&#39;<br><br>os.makedirs(output_directory, exist_ok = True)<br><br>for video_path in tqdm(video_paths):<br><br>  cap = cv2.VideoCapture(video_path) #cv2 is pythonic librabry of OpenCV<br>  #used to capture video frames from a video or a connected camera.<br><br>  # Get the video properties<br>  frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>  frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>  fps = cap.get(cv2.CAP_PROP_FPS)<br><br>  # Define the codec and create VideoWriter object<br>  # Define the codec to use (MP4V)<br>  fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br><br>  # Define the path where the output video will be saved<br><br>  output_path = os.path.join(output_directory, f&#39;output_{os.path.basename(video_path)}&#39;)<br>  out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))<br><br>  while cap.isOpened():<br>    ret, frame = cap.read() #reads the next frame from the video source<br>    #ret : boolean variable that indicates whether the frame was read successfully or not<br>    #frame : stores the actual video frame that was read by the cap.read() method.<br><br>    if not ret:<br>        break   #Exit loop if no more frames are available<br><br>    og_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>    #converts the color space of the input image (frame) from BGR to RGB.<br>    #frame: This is the input image, represented as a NumPy array or tensor.<br>    #BGR is the default color space used by OpenCV when reading images.<br>    #While Matplotlib expects images in RGB format when displaying.<br><br>    detection_results = model.predict(og_frame,classes = 0, conf = 0.6) #setting confidence detection thresshold = 0.6<br><br>    boxes = detection_results[0].boxes.xyxy.cpu().tolist()   # Boxes object for bbox outputs<br>    classes = detection_results[0].boxes.cls.cpu().tolist()  # Class probabilities for classification outputs<br>    scores = detection_results[0].boxes.conf.cpu().tolist()  # confidence score<br>    # and converting all of them into lists.<br><br>    for i in range(len(boxes)):<br>     box = boxes[i]<br>     cls = classes[i]<br>     score = round(scores[i],2)<br>     x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3])<br>     cv2.rectangle(og_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>     #cv2.putText(og_frame, str(score), (x1+10, y1-5), cv2.FONT_HERSHEY_SIMPLEX,<br>              #   0.5, (255,0,0), 1, cv2.LINE_AA)<br><br>    cv2.putText(og_frame, f&quot;Helmets Count : {len(boxes)}&quot;, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,<br>                    1, (0, 0, 0), 2, cv2.LINE_AA)<br>   # Syntax of PutText<br>   # (Image on which text will be drawn, Text to be drawn, Position of the text (top-left corner),Font type<br>   #  Font scale (size),Text color (in BGR format), Thickness of the text, Type of line for text rendering)<br><br>    out.write(cv2.cvtColor(og_frame, cv2.COLOR_RGB2BGR)) # writes back the prediceted frames to Video File one by one<br><br># these lines ensure that all resources associated<br># with video capture, video writing, and OpenCV windows are properly released and closed,<br># to free up system resources and to provide a clean exit for your program<br>cap.release()<br>out.release()<br>cv2.destroyAllWindows()</pre><p>We’re using the best model obtained from training in the Project 2. And we’re then using it to count the no. of helmets in some sample videos i’ve provided. We read the video feed using cv2 library and then applied the model we’ve on individual frames one by one. Then, we are putting all the predicted frames back to Video file. And yeah, that’s it! This is the whole code for this code. <strong>It can also be implemented on your Webcam with some modifications. Just put it on ChatGPT and it’ll modify it for your use-case.</strong></p><h3>What’s Next?</h3><p>We’ll be discussing and analyzing about the predictions and evaluation metrics in the upcoming blogs in great detail. Till then, Happy Learning!</p><p><strong>Do Follow and Upvote for more such content!!!</strong></p><p><a href="https://medium.com/subscribe/@ayushraj2349?source=publishing_settings---user_settings----------------------------------">Get an email whenever Ayush Raj publishes.</a></p><h3>List of Resources</h3><ul><li><strong>Must-Watch Videos for Optimizers</strong> : <a href="https://www.youtube.com/playlist?list=PLEAYkSg4uSQ1r-2XrJ_GBzzS6I-f8yfRU"><strong>Mitesh Khapra’s Deep Learning Course</strong></a></li><li><a href="https://distill.pub/2017/feature-visualization/">Distill: Feature Visualization</a> — This resource offers an excellent visual and intuitive understanding of the loss landscape in neural networks.</li><li><a href="https://www.jeremyjordan.me/nn-learning-rate/">Jeremy Jordan’s Blog on Learning Rates</a> — A comprehensive blog that dives into the intricacies of learning rates and their impact on training neural networks.</li><li><strong>In-Depth on Optimization</strong>: S<a href="https://www.ruder.io/optimizing-gradient-descent/">ebastian Ruder’s Blog on SGD</a> — An insightful blog that provides a deep dive into Stochastic Gradient Descent and its variants, including discussions on momentum. Read about SGD, challenges, Momentum, Adam and visualizations. If you can, read the whole blog — it’s a great resource.</li><li>Andrej Karpathy’s Blog — <a href="https://karpathy.github.io/2019/04/25/recipe/">A Recipe for Training Neural Networks</a></li><li><a href="https://cs231n.github.io/neural-networks-3/?ref=jeremyjordan.me#annealing-the-learning-rate">Andrej Karpathy’s Notes on Learning Rate</a> — For CS231n Course — Stanford</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f548ff193c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YOLO: Intuitive and Relatable Explanations]]></title>
            <link>https://medium.com/@ayushraj2349/yolo-intuitive-and-relatable-explanations-bb5e82d5f52d?source=rss-1b2a4d792fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb5e82d5f52d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[yolov8]]></category>
            <dc:creator><![CDATA[Ayush Raj]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 20:57:22 GMT</pubDate>
            <atom:updated>2024-02-20T20:57:22.228Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>This is the 3rd Installment in the Object Detection Series. In case, you missed the previous episodes, don’t worry — you can always come back here to map yourself: </strong><a href="https://medium.com/@ayushraj2349/unveiling-the-world-of-object-detection-from-theory-to-real-world-applications-building-3cace88e658c"><strong>Series Introductory Blog</strong></a><strong>.</strong></blockquote><h3>Introduction</h3><p>Ever wonder how self-driving cars “see” the road? Or how your phone identifies your face for unlocking? The answer lies in a revolutionary technology called YOLO.</p><p>YOLO or You Only Look Once, is a family of real-time object detection &amp; classification algorithms that have gained popularity in the field of computer vision. YOLO family gained this immense popularity due to its ability detect and classify multiple objects in an image or video frame in real-time. Previous methods for object detection, like R-CNN and its variations, used a pipeline to perform this task in two stages. This can be slow to run and also hard to optimize, because each individual component must be trained separately. Unlike them, YOLO, as the name suggests, instead of using two separate stages for box and category prediction, it employs a single stage network to simultaneously address both the problems, thus achieving a higher speed on inference, making it capable to solve real-world problems. For example, if you have a surveillance camera that needs to quickly identify multiple objects, the two-stage approach may struggle to provide fast results due to its sequential nature, potentially causing delays in critical applications while it will give the results in real-time. Recently, its latest version launch YOLOv8 has taken Computer Vision World by Storm by its crazy speed, accuracy and multiple real-time capabilities! YOLOv8 is the eighth version of the YOLO series, and it was developed by Alexey Bochkovskiy and the Ultralytics team.</p><p>Okay, so i guess enough of the talk! Let’s deep dive to unveil its groundbreaking technology and its amazing feats.</p><h3>Basics of YOLO</h3><p><strong><em>When YOLO is referred, it is basically YOLOv1. Although most of the basics discussed here remain same for all the versions</em>.</strong></p><p>YOLO takes the groundbreaking idea for object detection as to transform the image into a grid of cells, say S*S. Now, YOLO predicts for each for these S*S cells. This takes a significant leap from the conventional methods, like Faster R-CNN where you have to predict for all the proposals by its Region Proposal Network (RPN) which amounts to almost 2000, which is in contrast to what computation needs to be done here because S is generally about 7 to 10. So, YOLO has to predict for only around 100 region of proposals and that too it gets it done in a single forward pass only, rather than having separate networks for proposals and for prediction, and <strong>thus being called as Single-Stage Method</strong>. <strong>Another popular algorithm in this family is SSD</strong>. I will be explain it later in some other blog. For time being, let’s focus on YOLO. So, the decrease in network complexity and the no. of proposals laid the ground for Real-Time Detection where processing speed was the major bottleneck.</p><blockquote><strong>One Major Idea that give YOLO Models this huge success is their ability to have insights of Proportions. We’ll look into this shortly.</strong></blockquote><p>So, let’s look into the finer details with an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*tFTndM0Dg6ssP1DlHjZo8Q.jpeg" /></figure><p>Say S to be 7 here, just for illustrative purposes.</p><p>Now in these 49 cells, 1 cell for each object class takes the responsibility of predicting that object if the midpoint of its Ground Truth Box lies in that cell. Here, in the image above, the cell pointed will predict for Dog.</p><p>And for doing that, YOLO uses the concept of <strong>Anchor Boxes</strong>. These are a set of boxes of different shapes and sizes often in the Aspect Ratios of 1:1, 2:1 or 1:2, used to regress actual bounding box in terms of displacement. YOLO when used initially, it used only 2 such boxes as mentioned in the Research Paper.</p><blockquote><strong>The purpose of using Anchor Boxes:</strong></blockquote><p>I have a question for you. <strong>What will happen in the case when the same cell is the mid-point of 2 or more objects? </strong>Lets’ look at this image. What you will say?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*udvoHt1hOEq8WztbYm6few.jpeg" /></figure><p>Here comes the role of Anchor Boxes, as we know each cell outputs only 1 prediction and in this case, YOLO will fail.</p><p>So to counter this, they used Anchor Boxes. With the idea of anchor boxes what you are going to do is predefine 2 different shapes called Anchor Box 1 and Anchor Box 2. By this we can do two predictions with 2 anchor boxes. Allotment of Anchor Box will done on the basis of the value of IoU of that object bounding box with the Anchor Boxes. Generally threshold is taken as 0.5. So, here Box 1 will predict for the Girl and Box 2 will predict for the Car, as both mostly resembles the required shapes.</p><blockquote><strong>So, for each Anchor Box used in each cell, it outputs (5 + ‘C’) values, where ‘C’ denotes the number of classes. Let’s see each of these:</strong></blockquote><p>The first value represents the confidence score, also called <strong>(Box Confidence)</strong> (Pc) which to be put simply, tells us two things: <strong>what’s the likelihood of an object being in that box, and if there’s one, then how well does it fits the object?</strong> Hope you get the intuition. To put it mathematically, it is the product of objectness score (the model’s certainty that the box contains an object at all) <strong>(1st Part)</strong> with the Intersection over Union (IoU) between the predicted bounding box and the ground truth <strong>(2nd Part)</strong>. And i already assume you all have basic understanding of IoU. For those who don’t know,</p><blockquote><strong>How to judge whether predictions of Object Detection Algorithms are correct or not? Here comes the crucial role of IoU into play:</strong></blockquote><p>IOU = Area of Intersection / Area of Union</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*IpyzA6ta94DisP8y8oQqgw.jpeg" /></figure><p>The next four values are for the center coordinates (x,y), width &amp; height of the predicted box.</p><p>Then the ‘C’ values simply are the probability distribution over all the classes that gives the likelihood of object in that box being associated to that class <strong>(Class Confidence) </strong>which simplifies to taking the conditional probability of the class given that an object has been detected (P(Class_i|Object)) multiplying that with the objectness score and the IoU <strong>(Box Confidence)</strong>.</p><p><strong>But here’s a catch! The highest in these ‘C’ values should not be interpreted as the output confidence score as usually we do in the case of Image Classification or Detection.</strong></p><p>Infact, the Confidence Score that the YOLO outputs is the product of <strong>Class Confidence</strong> and the <strong>Box Confidence </strong>which enables it to balance between how certain it is that a box contains an object and how certain it is about which class this object belongs to.</p><p>So, the output vector for each cell, having 2 Anchor Boxes as mentioned above will look something like this : [Pc1, x1, y1, h1, w1, c1, c2, c3, Pc2, x2, y2, h2, w2, c1, c2, c3], vector of size (16,1).</p><p>And in context of our Project whose details i will be sharing in due course of time, c1, c2 &amp; c3 will be helmet, head &amp; person respectively.</p><blockquote><strong>So, the output of YOLO will be a tensor of shape [S*S*K*(5+C)] where K is the no. of output boxes and C is the number of Classes.</strong></blockquote><p>Let’s give you an example. Remember the Girl &amp; Car Example in the Anchor Box Section? That Cell’s output will be, assuming c1=girl, c2=car, c3=bike :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*xt4D9QQhdmFlKXqg878DZA.jpeg" /></figure><p>Here, (Pc) value is 1 for both boxes, as obvious from the image. And the Box 1 &amp; Box 2 was for girl &amp; car, and so are the results as expected.</p><blockquote><strong>Now, I guess we’ve enough to dive into the concept of insights of Proportions. What it means is that any cell of the grid while focusing on its area is aware of the bigger picture. Each cell has some context of it. This means it’s not that the Model only knows area of one cell at a time, it takes into account the whole image, but focusing on that area only. So, each cell is not restricted to predict bounding box inside its area only, it can predict larger than itself using its knowledge of objects and their proportions (x,y,w,h). A good analogy i think to relate this magic of YOLO will be us, Humans, how we can recognize a object just by seeing a part of it. For example, if i show you only the arms of a person, you can predict that this is a person and also draw the probable bounding box because you’re aware of the proportions. Hope that makes sense to you!</strong></blockquote><p>So, YOLO breaks down to a combination of regression and classification problem. Hope you already got the intuition before I wrote this! :)</p><p>Okay, so now we are going to know NMS which is Non-Max Suppression. It is a post processing step but is as important as the other stages. Let’s Look at this:</p><blockquote>I have one more question for you which will serve as the intuition for this: <strong>There can be multiple bounding boxes for each object in an image, so how to deal with it?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*5fZMYfLbnL_lqxuUfA8MrA.jpeg" /><figcaption>Multiple Detections for each Objects</figcaption></figure><p>Yup, NMS will tackle this. If used without NMS, any model will predict outputs like this. As you’ve already understood that this is not what we wanted. Model also predicts many redundant overlapping boxes.</p><p><strong><em>Okay, but why will it happen?</em></strong></p><p>Because you are running image classification and localization algorithm on every grid cell, see, it’s always possible that many of the cells say that their ‘Pc’ Class Probability or chance of having that same object in that cell is highest. It’s quite intuitive, because see we know that it’s one cell’s responsibility to predict object containing its midpoint but you can think, that nearby cells which are close to the mid-point will also claim that they have the object with varying confidence scores. And hence, you get your answer. :)</p><p><strong><em>So, NMS or Non-Max Suppression, suppresses the ones which are not maximum, and hence get its name. It is a key technique applied per class to make sure your algorithm detects objects only once.</em></strong></p><h4><strong><em>How this Works?</em></strong></h4><ol><li>Firstly, it removes all bounding boxes of each class which have scores less than a particular threshold (generally, this value is taken as 0.6).</li><li>Then it looks for probabilities (confidence scores) associated with each of these detections for a particular class.</li><li>Then, it takes largest score which is most confident detection for that class.</li><li>Having done that, the NMS part looks for all remaining bounding boxes of that class and chooses all those bounding boxes which have high Intersection over Union (IOU) with the bounding box of highest score, (generally value of IoU is taken as 0.5) and suppresses them.</li><li>Then we look for remaining bounding box and find highest score and again NMS looks for remaining bounding boxes which have high IOU with bounding box of high score and then they will get suppressed.</li></ol><p>By doing this for every object we get only one bounding box for each object.</p><p>So for this example:</p><ol><li>Let’s take the threshold value to be ≤ 0.7.</li><li>The box with score 0.6 for Car 1 will get discarded.</li><li>It takes largest score which is 0.9 in this case for Car 1 and 0.8 for Car 2.</li><li>Now, It checks IoU for all the remaining bounding boxes for Car 1 and Car 2 (i.e. for 0.7 for both Car 1 and Car 2).</li><li>Now, NMS will suppress 0.7 for car 1 as it has high IoU with 0.9 for car 1 and 0.7 for car 2 as it has high IOU with respect to bounding box of score = 0.8, so like this we get only one bounding box each for car 1 &amp; car 2 which are highlighted in the image.</li><li>It’s just a special case where you got rid off of all the redundant boxes in one go. If that persists, you just have to do all of this in a loop!</li></ol><p>So, this wraps up our YOLO algorithm.</p><p>Phew, that was indeed a lot! I tried to keep it simpler for you. Hope you get it!</p><h3>Limitations of YOLO v1 :</h3><ol><li><strong>Fixed Number of Predictions:</strong> YOLOv1 predicted a fixed number of bounding boxes per grid cell ( in our case total 49 predictions are possible because we have 49 grid cells), which might not be optimal for images with varying object counts.</li><li><strong>Poor Localization : </strong>YOLOv1 had trouble accurately figuring out where objects were in images and how big they were. It often drew boxes that didn’t fit objects well, especially if objects were small or close together. This happened because YOLOv1 couldn’t handle different object sizes very effectively, and its pictures lost some fine details, making its guesses less precise</li><li><strong>Limited in Detecting Small Objects:</strong> YOLOv1 struggled to accurately detect and localize small objects within images, as its single-scale approach wasn’t well-suited for handling objects of varying sizes.</li></ol><h3>Evolution from YOLO to YOLOv8</h3><p>Firstly, I will be going through the evolution from YOLO to YOLOv8 very briefly just to give you an idea. It’s optional, if you’re not interested, just skip this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apjTdTZmOINo8Yj9K4_7HQ.jpeg" /><figcaption>Credit : Encord</figcaption></figure><p><a href="https://arxiv.org/abs/1506.02640">YOLO</a> (You Only Look Once), a popular object detection and image segmentation model, was developed by Joseph Redmon and Ali Farhadi at the University of Washington. Launched in 2015, YOLO quickly gained popularity for its high speed and accuracy.</p><ul><li><a href="https://arxiv.org/abs/1612.08242">YOLOv2</a>, released in 2016, improved the original model by incorporating batch normalization, anchor boxes, and dimension clusters.</li><li><a href="https://pjreddie.com/media/files/papers/YOLOv3.pdf">YOLOv3</a>, launched in 2018, further enhanced the model’s performance using a more efficient backbone network, multiple anchors and spatial pyramid pooling.</li><li><a href="https://arxiv.org/abs/2004.10934">YOLOv4</a> was released in 2020, introducing innovations like Mosaic data augmentation, a new anchor-free detection head, and a new loss function.</li><li><a href="https://github.com/ultralytics/yolov5">YOLOv5</a> further improved the model’s performance and added new features such as hyperparameter optimization, integrated experiment tracking and automatic export to popular export formats.</li><li><a href="https://github.com/meituan/YOLOv6">YOLOv6</a> was open-sourced by <a href="https://about.meituan.com/">Meituan</a> in 2022 and is in use in many of the company’s autonomous delivery robots.</li><li><a href="https://github.com/WongKinYiu/yolov7">YOLOv7</a> added additional tasks such as pose estimation on the COCO keypoints dataset.</li><li><a href="https://github.com/ultralytics/ultralytics">YOLOv8</a> is the latest version of YOLO by Ultralytics. As a cutting-edge, state-of-the-art (SOTA) model, YOLOv8 builds on the success of previous versions, introducing new features and improvements for enhanced performance, flexibility, and efficiency. YOLOv8 supports a full range of vision AI tasks, including <a href="https://docs.ultralytics.com/tasks/detect/">detection</a>, <a href="https://docs.ultralytics.com/tasks/segment/">segmentation</a>, <a href="https://docs.ultralytics.com/tasks/pose/">pose estimation</a>, <a href="https://docs.ultralytics.com/modes/track/">tracking</a>, and <a href="https://docs.ultralytics.com/tasks/classify/">classification</a>. This versatility allows users to leverage YOLOv8’s capabilities across diverse applications and domains.</li><li><strong>And Recently, just a few weeks ago, on Jan 10,2024, They announced the upgrade of YOLOv8, v8.1. </strong>In this they introduced the concept of <strong>Oriented Bounding Box (OBB)</strong> which marks a significant step in object detection, especially for angled or rotated objects, enhancing accuracy and reducing background noise in various applications such as aerial imagery and text detection. Simple intuition is that before we simply make rectangular boxes which may get less precise for tilted objects. This is solution for this problem.</li></ul><p>So, you see Innovation is going on and on! This Computer Vision community, The AI community in general never sleeps, haha! But, really a lot is yet to come!</p><h3>Why should I use YOLOv8?</h3><p>A few of the main reasons you should consider using YOLOv8 in your next computer vision project are:</p><ul><li><strong>The Best Reason ever can be it’s almost no-code requirement for implementation.</strong></li><li>YOLOv8 has better accuracy than previous YOLO models.</li><li>The latest YOLOv8 implementation comes with a lot of new features, we especially like the user-friendly CLI and GitHub repo.</li><li>It supports object detection, instance segmentation, and image classification.</li></ul><p>The community around YOLO is incredible, just search for any edition of the YOLO model and you’ll find hundreds of tutorials, videos, and articles. <strong>I must mention, I learned a lot just by discussing in the GitHub community and from the Documentation they’ve provided. These are best resources one can get. I’ll provide all the relevant links in the References.</strong></p><ul><li>Training of YOLOv8 will be probably faster than the other two-stage object detection models.</li></ul><p>One reason not to use YOLOv8:</p><ul><li>At the current time YOLOv8 does <a href="https://www.stereolabs.com/blog/performance-of-yolo-v5-v7-and-v8/">not support models</a> trained in 1280 (in pixels) resolution, thus if you’re looking to run inference at high resolution it is not recommended to use YOLOv8.</li></ul><h3>How does YOLOv8 compare to previous models?</h3><p>The Ultralytics team has once again benchmarked YOLOv8 against the COCO dataset and achieved impressive results compared to previous YOLO versions across all five model sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*h3LnfN-t-ZIzlCWR" /></figure><p><em>Source: </em><a href="https://github.com/ultralytics/ultralytics"><em>GitHub</em></a></p><p>When comparing the performance of the different YOLO lineages and model sizes on the COCO dataset we want to compare different metrics.</p><ul><li><strong>Performance: </strong>Mean average precision (mAP)</li><li><strong>Speed: </strong>Speed of the inference (In fps)</li><li><strong>Compute (cost): </strong>The size of the model in FLOPs and params</li></ul><blockquote>YOLOv8 is available in 5 different sizes based on the number of parameters and complexity. They are: nano, small, medium, large and extra large.</blockquote><p>For the object detection comparison of the 5 model sizes, The YOLOv8m model achieved an <strong>mAP of 50.2%</strong> on the COCO dataset, whereas the largest model, YOLOv8x achieved <strong>53.9%</strong> with more than double the number of parameters.</p><blockquote><strong>We’ve used the medium version (YOLOv8m) for our Helmet Detection Project.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*pI2bPc6G0sed4W1F" /></figure><p><em>Source: </em><a href="https://github.com/ultralytics/ultralytics"><em>GitHub</em></a></p><p><strong>Overall, YOLOv8’s high accuracy and performance make it a strong contender for your next computer vision project, just like it did for mine!.</strong></p><p>Whether you are looking to implement object detection in a commercial product, or simply want to experiment with the latest computer vision technologies, YOLOv8 is a state-of-the-art model that you should consider.</p><p>Next, we will analyze the architecture and design of the model.</p><h3>Implementing YOLOv8</h3><p>Let us look at how to use and implement YOLOv8 into your workflows. The model comes bundled with the following<a href="https://learnopencv.com/ultralytics-yolov8/"> pre-trained models</a> that can be utilized off-the-shelf in your computer vision projects to achieve better model performance:</p><ul><li><strong>Instance segmentation</strong> models trained on the COCO segmentation dataset with an image resolution of 640.</li><li><strong>Image classification </strong>models pre-trained on the ImageNet dataset with an image resolution of 224.</li><li><strong>Object Detection</strong> models trained on the COCO detection dataset with an image resolution of 640.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*xFcCI1n4ri8gt8bc" /></figure><p><em>Source: </em><a href="https://ultralytics.com/article/Introducing-Ultralytics-YOLOv8"><em>Ultralytics. </em></a><em>Example of Classification, Object Detection, and Segmentation.</em></p><p>In the next section, we will cover how to access YOLO via your CLI, python, environment, and lastly in Encord’s Platform.</p><h3>How do I use the YOLOv8 CLI?</h3><p>YOLOv8 can be accessed easily via the CLI and used on any type of dataset.</p><pre>!yolo task=detect \ mode=predict \ model=yolov8n.pt \ source=&quot;image.jpg&quot;</pre><p>To use it simply insert the following commands:</p><ul><li>task in [detect, classify, segment]</li><li>mode in [train, predict, val, export]</li><li>model as an uninitialized .yaml or as a previously trained .pt file</li><li>Source as the path/to/data</li></ul><h3>Can I pip install YOLOv8?</h3><p>Complementary to the CLI, YOLOv8 is also distributed as a<a href="https://pypi.org/project/yolov8/"> PIP package</a>, perfect for all Python environments. This makes local development a little harder but unlocks all of the possibilities of weaving YOLOv8 into your Python code.</p><p>You can clone it from GitHub:</p><pre>git clone https://github.com/ultralytics/ultralytics.git</pre><p>Or pip install from pip:</p><pre>pip install ultralytics</pre><p>After pip installing you can import a model and use it in your favorite Python environment:</p><pre>from ultralytics import YOLO <br># Load a model model = YOLO(&quot;yolov8n.pt&quot;) <br># load a pretrained model <br># Use the model <br>results = model.train(data=&quot;coco128.yaml&quot;, epochs=5) # train the model <br>results = model.val() # evaluate model performance on the validation data set <br>results = model(&quot;https://ultralytics.com/images/cat.jpg&quot;) # predict on an image<br>success = YOLO(&quot;yolov8n.pt&quot;).export(format=&quot;onnx&quot;) # export a model to ONNX</pre><h3>What is the Annotation Format of YOLOv8?</h3><p>YOLOv8 has a simple annotation format which is the same as the YOLOv5 <a href="https://pytorch.org/">PyTorch</a> TXT annotation format, a modified version of the Darknet annotation format.</p><p>Every image sample has one .txt file with one line for each bounding box. The format of each row is presented as follows:</p><pre>class_id center_x center_y width height</pre><p>Notice that each field is space delimited and the coordinates are normalized from zero to one.</p><p><strong>YOLOv8 annotation format example:</strong></p><pre>1: 1 0.317 0.30354206008 0.114 0.173819742489 <br>2: 1 0.694 0.33726094420 0.156 0.23605150214 <br>3: 1 0.395 0.32257467811 0.13 0.195278969957</pre><p>The data.yaml folder contains information used by the model to locate images and map class names to the class ids.</p><pre>train: ../train/images <br>test: ../test/images <br>val: ../valid/images <br><br>nc: 5 <br>names: [&#39;fish&#39;, &#39;cat&#39;, &#39;person&#39;, &#39;dog&#39;, &#39;shark&#39;]</pre><h3>Conclusion</h3><p>In conclusion, YOLO, and particularly its latest iteration YOLOv8, has revolutionized the field of computer vision with its speed, accuracy, and ease of use. From self-driving cars to surveillance systems, its applications are vast and its potential for future advancements is even more exciting. Whether you’re a developer, researcher, or simply curious about cutting-edge technology, YOLO is definitely worth exploring.</p><p>This blog has only scratched the surface of the fascinating world of YOLO. Now that you’re equipped with the basics, why not start experimenting? YOLO’s journey is far from over, and its potential to transform our world is immense.</p><p><strong>Do follow and Upvote for more such content!!!</strong></p><p><a href="https://medium.com/subscribe/@ayushraj2349?source=publishing_settings---user_settings----------------------------------">Get an email whenever Ayush Raj publishes.</a></p><h3>References</h3><p><a href="https://arxiv.org/abs/1506.02640">YOLO Research Paper</a></p><p><a href="https://www.youtube.com/watch?v=ArPaAX_PhIs&amp;list=PLkDaE6sCZn6Gl29AoE31iwdVwSG-KnDzF">Andrew NG Lectures</a></p><p><a href="https://github.com/orgs/ultralytics/discussions/">GitHub Discussions, Ultralytics</a></p><p><a href="https://docs.ultralytics.com/">YOLOv8 Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb5e82d5f52d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Unveiling the World of Object Detection: From Theory to Real-World Applications & Building…]]></title>
            <link>https://medium.com/@ayushraj2349/unveiling-the-world-of-object-detection-from-theory-to-real-world-applications-building-3cace88e658c?source=rss-1b2a4d792fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cace88e658c</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[faster-r-cnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[yolov8]]></category>
            <dc:creator><![CDATA[Ayush Raj]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 10:34:13 GMT</pubDate>
            <atom:updated>2024-02-22T00:46:46.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Unveiling the World of Object Detection: From Theory to Real-World Applications &amp; Building Projects on one of them”</h3><h3>Acknowledgements</h3><p><strong><em>Before we dive into the series, we would like to extend our heartfelt gratitude to my mentor </em></strong><a href="https://medium.com/u/a1d407c584d5"><strong><em>Priyam Dalmia</em></strong></a><strong><em> Sir for his constant support throughout this Journey. His guidance and expertise have been instrumental in shaping the direction of this Series. His feedback, wisdom, and mentorship have been invaluable, and I am truly fortunate to have had the opportunity to learn from him. Also, I would also like to express my deepest appreciation to my dear friends for their invaluable support and encouragement.</em></strong></p><h3>Structure of this Blog Series</h3><p>1. <strong>Introduction to Object Detection and Safety Helmet Detection Projects:</strong></p><ul><li>The series kicks off with an introductory blog post that serves as a gateway into the world of object detection. We provide a brief overview of object detection, its significance in computer vision, and set the stage for the following discussions. Additionally, we introduce readers to the focus of our series by discussing the three safety helmet detection projects. These projects will be used throughout the series as practical examples to illustrate concepts and implementations.</li></ul><p>2. <strong>Introduction to Faster R-CNN:</strong></p><ul><li>In the first dedicated blog post, we’ll delve into Faster R-CNN, a highly accurate and efficient object detection algorithm. Readers are introduced to the architecture, key components, and the principles that make Faster R-CNN a cornerstone in computer vision applications.</li></ul><p>3. <strong>Introduction to YOLO (You Only Look Once):</strong></p><ul><li>The series continues with an exploration of YOLO, known for its speed and real-time capabilities. We explain the unique architecture of YOLO, its advantages, and applications in various domains, setting the stage for comparisons and contrasts with Faster R-CNN.</li></ul><p>4. <strong>Real-World Applications of Object Detection:</strong></p><ul><li>Moving beyond theory, the series delves into the practical side of object detection. In this blog post, you explore real-world applications of both Faster R-CNN and YOLO. Case studies and examples highlight the impact of these algorithms in areas such as autonomous vehicles, surveillance systems, and Industrial Quality Control.</li></ul><p>5. <strong>Code Insights and Implementation Tips:</strong></p><ul><li>Readers get hands-on with code insights and practical tips for implementing Faster R-CNN and YOLO in their own projects. This blog post provides code snippets, best practices, and experiences from our safety helmet detection projects, offering a practical guide for enthusiasts and beginners alike.</li></ul><p>6. <strong>Understanding Evaluation Metrics in Object Detection:</strong></p><ul><li>Object detection models are assessed using specific metrics to measure their performance. This blog post explains key evaluation metrics such as precision, recall, and the mAP score. Readers gain a deeper understanding of how to evaluate and compare the effectiveness of object detection models.</li></ul><p>7. <strong>Visualizing Results and Performance Analysis:</strong></p><ul><li>Wrapping up the series, we focus on visualizing results and conducting performance analysis for Faster R-CNN and YOLO models. Using our safety helmet detection projects as examples, we showcase model outputs, discuss analysis techniques, and offer insights into optimizing model performance.</li></ul><p>Through this comprehensive series, readers are taken on a journey from the fundamentals of object detection, through in-depth explorations of Faster R-CNN and YOLO, to practical implementations and performance evaluations. The Safety Helmet Detection Project serves as practical examples, grounding the theoretical discussions in real-world applications. Whether readers are beginners or seasoned enthusiasts in Computer Vision, this series aims to provide valuable insights and guidance into the fascinating world of object detection.</p><h3>Read List of the Series</h3><p>I’ll update all the links of the blogs of this series here as soon as they get published in due course of time.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>All Links Updated in Chronological Order:</strong></p><p><a href="https://medium.com/@ayushraj2349/unveiling-the-world-of-object-detection-from-theory-to-real-world-applications-building-3cace88e658c"><strong>Series Introductory Blog</strong></a></p><p><a href="https://medium.com/thedeephub/faster-r-cnn-object-detection-5dfe77104e31"><strong>Faster R-CNN: Object Detection</strong></a></p><p><a href="https://medium.com/@ayushraj2349/yolo-intuitive-and-relatable-explanations-bb5e82d5f52d"><strong>YOLO: Intuitive and Relatable Explanations</strong></a></p><p><a href="https://medium.com/@vkt08/enhancing-safety-a-computer-vision-approach-to-helmet-detection-c5a48a7275d2"><strong>Enhancing Safety: A Computer Vision Approach to Helmet Detection</strong></a></p><p><a href="https://medium.com/@ayushraj2349/implementing-faster-r-cnn-and-yolov8-for-the-helmet-detection-project-the-coding-aspect-8f548ff193c5"><strong>Implementing Faster R-CNN and YOLOv8 for the Helmet Detection Project: The Coding Aspect</strong></a></p><p><a href="https://medium.com/@vkt08/seeing-clearly-demystifying-object-detection-performance-metrics-58ac103ae6b3"><strong>Seeing Clearly: Demystifying Object Detection Performance Metrics</strong></a></p><p><a href="https://medium.com/@ayushraj2349/the-final-chapter-visualizing-predictions-and-analyzing-the-results-17fd996e1104"><strong>The Final Chapter: Visualizing Predictions and Analyzing the Results</strong></a></p><p><strong>Okay. So, Let’s Start here with our Introductory Blog:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZE5YXLFlbrZZabG1kWBHPQ.jpeg" /></figure><h3>Welcome to the World of Deep Learning!</h3><p>Hey all,</p><p>Welcome to the kickoff of our exciting new blog series dedicated to object detection! Over the next several posts, we’ll be diving deep into the fascinating world of computer vision and exploring the intricacies of object detection algorithms, techniques, and applications. From understanding the fundamentals of convolutional neural networks to exploring advanced architectures like YOLO, we’ll cover it all.</p><blockquote><strong><em>But that’s not all — we’ll also embark on a thrilling project where we’ll build our very own helmet detection system from scratch.</em></strong></blockquote><p>Get ready to roll up your sleeves, code alongside us, and witness firsthand how to harness the power of deep learning to detect objects in images and videos. Whether you’re a beginner looking to grasp the basics or a seasoned practitioner eager to expand your knowledge, this series promises to be an enlightening journey into the world of object detection. So, without further ado, let’s dive in and start building something incredible together!</p><h3>Object Detection: Seeing the World Like Machines Do</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nq82UA7n7G9dhJt7WsQkqA.jpeg" /><figcaption>Credit: Roboflow</figcaption></figure><p>Object detection is a branch of computer vision that enables machines to identify and locate objects within images and videos. Imagine a self-driving car recognizing pedestrians and traffic signs, or a medical imaging system highlighting potential tumors. These are just a few examples of how object detection impacts our world.</p><p><strong>How it works:</strong></p><p>Object detection algorithms typically involve two steps:</p><ol><li><strong>Feature extraction:</strong> The algorithm analyzes the image or video frame, extracting key features like color, shape, and texture.</li><li><strong>Classification and localization:</strong> Using these features, the algorithm predicts the presence and location of specific objects within the image.</li></ol><p><strong>Real-world applications:</strong></p><p>Object detection has a wide range of applications across various sectors:</p><ul><li><strong>Self-driving cars:</strong> Detecting pedestrians, vehicles, and traffic signals for safe navigation.</li><li><strong>Security and surveillance:</strong> Identifying suspicious activity or unwanted objects in public spaces. <strong><em>And this is the area where our Project delves into!</em></strong></li><li><strong>Retail and manufacturing:</strong> Automating inventory management and product inspection.</li><li><strong>Medical imaging:</strong> Identifying abnormalities in X-rays and other medical images.</li><li><strong>Robotics:</strong> Enabling robots to interact with their environment safely and efficiently.</li><li><strong>Augmented reality:</strong> Overlaying virtual objects onto the real world in real-time.</li></ul><p><strong>Benefits:</strong></p><ul><li><strong>Increased efficiency and automation:</strong> Reduces manual tasks and improves accuracy.</li><li><strong>Enhanced safety and security:</strong> Detects potential risks and hazards.</li><li><strong>Improved data analysis:</strong> Provides valuable insights from images and videos.</li><li><strong>New possibilities:</strong> Enables innovative applications in various fields.</li></ul><p><strong>Limitations:</strong></p><ul><li><strong>Computational cost:</strong> Requires powerful hardware and can be resource-intensive.</li><li><strong>Data requirements:</strong> Training models often requires large amounts of labeled data.</li><li><strong>Accuracy challenges:</strong> Performance can vary depending on lighting, occlusion, and object complexity.</li></ul><p><strong>Future outlook:</strong></p><p>As object detection technology continues to evolve, we can expect even more sophisticated and accurate algorithms, leading to exciting new applications across various industries.</p><h3><strong>Our Project on Safety Helmet Detection</strong></h3><p>Yes, Finally, The Section you’ll be most interested into!</p><h3><strong><em>Introducing our groundbreaking project on Safety Helmet Detection</em></strong></h3><p>A game-changer in workplace safety. Through the lens of computer vision, we’ve developed a sophisticated system capable of identifying and enforcing the use of safety helmets in hazardous environments.</p><blockquote><strong>Our cutting-edge technology not only detects the presence of helmets but also ensures compliance, minimizing the risk of head injuries and saving lives.</strong></blockquote><p>Join us as we showcase the power of AI in creating safer workspaces and revolutionizing industry standards. With our innovative solution, safety is no longer an option — it’s a guarantee!</p><p>In this Section, We’ll give you a brief intro to all our Projects that we’ve have built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*XoGDEyP4bjZmCynmtmjyDA.jpeg" /><figcaption>Safety Helmet Detection in Computer Vision</figcaption></figure><h3>Project 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*28eF_wVua5BdY7WkGgh43w.png" /><figcaption>Predictions on a random image of the test dataset. Green &amp; Yellow Boxes represent the actual &amp; predicted boxes respectively.</figcaption></figure><p>In this Project, we’ve implemented this system using the conventional two-stage method, <strong>Faster R-CNN</strong>. Though it may be debatable to most of you, as it has become one of the older approaches for Object Detection, because of its incompatibility in Real-Time Detection due to the slow processing speed. But don’t forget its prowess in terms of accuracy and precision. Although, in our experimentation, we didn’t get the expected results. Don’t Worry, we’ve tried to find the one of the best optimal solution in our next Project.</p><h3><strong>Project 2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*6JqNtRqe0qmscfMVqSwF2w.png" /><figcaption>Predictions on a random Image of the Test Dataset</figcaption></figure><p><strong><em>Till now, you must be wondering, Why the hell are they not updated?</em></strong> Haha, Don’t worry, here we come with the State of the Art Model <strong>YOLOv8</strong>, as you all were expecting.</p><p>In this Project, we’ve pushed the boundaries even further with YOLO (You Only Look Once), a revolutionary object detection architecture known for its speed and versatility. By leveraging YOLO’s advanced capabilities, we’ve created an ultra-fast safety helmet detection system that delivers lightning-fast results without compromising accuracy.</p><p><strong>“Now, Get ready to be amazed and thrilled by the astonishing video results that will leave you in awe and excitement!” Here’s one:</strong></p><p><a href="https://drive.google.com/file/d/120b5KMOPtmE3LcMxSEjO-vmMHfaVCFLs/view?usp=sharing">20sec.avi</a></p><p>And, we think we feel satisfied by the results given by YOLOv8.</p><h3><strong>Project 3: Object Counting using YOLOv8</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sc1V9KynlN3V75HjUnrnVw.png" /><figcaption>Snapshot 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6OEiHX5OMi-8nZ7keyn6g.png" /><figcaption>Snapshot 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OslCxC7FLRYZXwghvhqVVQ.png" /><figcaption>Snapshot 3</figcaption></figure><p>And the last one! A smaller yet powerful Project build using YOLOv8 to showcase one out of many real-world applications. You already saw the results, these are the snapshots taken from the <a href="https://drive.google.com/file/d/1SoQ-8ZIPyksjLGMG_AfXmdALjBHaBlRN/view?usp=sharing">output video</a>. Isn’t it fascinating?</p><blockquote><strong>This tool simply plots the bounding boxes of Helmets without confidence score (else it will become clumsy, just to look clean) and displays the current count of Helmets in the videos.</strong></blockquote><p>This tool can be very useful for real-time video surveillance, traffic monitoring, and autonomous systems.</p><p>You can also use more features like ability to track objects, maintain identities, handle occlusions and noise in this tool.</p><blockquote><strong>For giving you just a simple example, Traffic Camera — this tool can be implemented in city surveillance cameras to give an automated estimate of how well are the traffic rules being followed (if helmets are mandatory).</strong></blockquote><p><strong>“This small tool is incredibly useful; you wouldn’t believe it until you see it in action!” So, Here’s one:</strong></p><p><a href="https://drive.google.com/file/d/1SoQ-8ZIPyksjLGMG_AfXmdALjBHaBlRN/view?usp=sharing">output_1.mp4</a></p><blockquote><strong>Explore our </strong><a href="https://github.com/ayushraj2349/Object-Detection-in-Computer-Vision"><strong>GitHub repository</strong></a><strong> for all the three projects, where we’ve meticulously crafted organization and seamless compilation, offering a user-friendly journey through our innovative solutions’ codebases!</strong></blockquote><h3>Okay. But, why do we actually care?</h3><p>The Safety Helmet Project is paramount for workplace safety. <strong>Utilizing cutting-edge technologies like Faster R-CNN and YOLO, it enforces the mandatory use of safety helmets in hazardous environments, saving lives and promoting a culture of safety consciousness. This project showcases the transformative power of computer vision in enhancing safety standards across industries, reaffirming our commitment to protecting workers’ well-being and ensuring a secure working environment for all</strong>. The importance is so immense that we decided to dedicate a separate blog on this, whose link will be updated.</p><p><strong>And, yes, Don’t Worry! We’ll deep dive into all the gory and technical details you want to know.</strong> From the intricacies of the algorithms to the nuances of implementation, we’ll leave no stone unturned to provide the insights you seek. So, keep an eye out for our next installments, where we’ll unravel the mysteries behind the scenes.</p><blockquote><strong><em>This Blog Series is a product of our dedicated teamwork. We strive for accuracy, but mistakes can happen. If you notice any errors or typos, please point them out and let us know in the comments below.</em></strong></blockquote><p><strong>If this helps, Do Follow and Upvote for more such content and for giving this blog a better reach!</strong></p><p><strong>Together, let’s journey towards knowledge and excellence. Don’t miss out — join our community today!!!</strong></p><ul><li><a href="https://medium.com/subscribe/@ayushraj2349?source=publishing_settings---user_settings----------------------------------">Get an email whenever Ayush Raj publishes.</a></li><li><a href="https://medium.com/subscribe/@vkt08?source=publishing_settings---user_settings----------------------------------">Get an email whenever Vikash Kumar Thakur publishes.</a></li></ul><h3><strong>About the Authors</strong></h3><p><a href="https://medium.com/@ayushraj2349">Ayush Raj</a></p><p><a href="https://medium.com/@vkt08">Vikash Kumar Thakur</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cace88e658c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>