<?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 Aleynaahukmet on Medium]]></title>
        <description><![CDATA[Stories by Aleynaahukmet on Medium]]></description>
        <link>https://medium.com/@aleynaahukmet?source=rss-af1209f5ccc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I49XLFVYIHFtJUPBDoCymQ.jpeg</url>
            <title>Stories by Aleynaahukmet on Medium</title>
            <link>https://medium.com/@aleynaahukmet?source=rss-af1209f5ccc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:54:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aleynaahukmet/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[Distilling Efficiency: Experiments in Compressing BAAI/bge-m3 using a Synthetic Dataset]]></title>
            <link>https://medium.com/altai-dev/distilling-efficiency-experiments-in-compressing-baai-bge-m3-using-a-synthetic-dataset-9430e21c6b8f?source=rss-af1209f5ccc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9430e21c6b8f</guid>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[knowledge-distillation]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Aleynaahukmet]]></dc:creator>
            <pubDate>Fri, 16 May 2025 07:34:38 GMT</pubDate>
            <atom:updated>2025-05-16T10:38:15.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*-1QCr0VYZ4c6OoHCqSpcdw.png" /></figure><h3><strong>Introduction</strong></h3><p>The rapid progress in Natural Language Processing (NLP) is mainly due to the development of large and complex neural network models. While these models perform very well, their <strong>size and high computational needs</strong> make them hard to use in real-world applications, especially for specific types of text. Many use cases — like semantic search and analyzing synthetic questions — could benefit from AI tools, but large models are often too <strong>costly and slow</strong>. This study explores distilling the powerful multilingual <a href="https://huggingface.co/BAAI/bge-m3">BAAI/bge-m3 </a>text embedding model into smaller versions with 8, 6, and 4 layers. The goal is to find the right balance between <strong>model size, speed, and retrieval performance</strong> using a synthetic dataset of contextual texts and generated questions. As NLP models become more complex, distillation helps make advanced AI more accessible and practical, especially for resource-limited needs.</p><h3><strong>1. Background</strong></h3><p><strong>1.1 What is Model Distillation?</strong></p><p>Model distillation — also known as <strong>knowledge distillation</strong> — is a technique used to compress large, powerful models by training smaller models to replicate their behavior. First introduced by <strong>Hinton et al. (2015)</strong>, this approach allows a <strong>smaller “student” model</strong> to approximate the performance of a <strong>larger “teacher” model</strong> while using significantly fewer parameters. The result is faster inference, lower memory requirements, and reduced deployment costs — ideal for real-world applications that require scalability and efficiency.</p><p>At the heart of this process is the idea that the teacher model has already learned rich patterns and decision boundaries from extensive training data. Instead of training the student model solely on standard “hard” labels (like class IDs), distillation trains it on the <strong>“soft targets”</strong> produced by the teacher model. These soft targets — such as the <strong>probability distributions</strong> generated at the output layer — convey more nuanced information about how the teacher interprets the data. This helps the student not just learn the correct answers, but also gain insight into the reasoning behind the teacher’s decisions.</p><p>In this work, the <strong>BAAI/bge-m3</strong> model serves as the teacher. It is a <strong>state-of-the-art text embedding model</strong>, known for its effectiveness and versatility in a wide range of retrieval and representation tasks. It stands out in three important dimensions:</p><ul><li><strong>Multi-Functionality</strong>: BAAI/bge-m3 supports dense retrieval, sparse retrieval (based on lexical matching), and multi-vector retrieval — all within a single model architecture.</li><li><strong>Multi-Linguality</strong>: It works across <strong>more than 100 languages</strong>, mapping them into a shared semantic space to enable both monolingual and cross-lingual search.</li><li><strong>Multi-Granularity</strong>: The model handles input texts of varying lengths, from short phrases to full-length documents — <strong>up to 8192 tokens</strong> — making it suitable for diverse use cases.</li></ul><p>By distilling this teacher into smaller variants, the goal is to retain as much of its semantic power as possible, while greatly improving efficiency for deployment in real-world systems.</p><h3><strong>2. Distilled Variants</strong></h3><p>The primary goal of this work was to <strong>create smaller, faster versions of the BAAI/bge-m3 model</strong> while retaining as much of its semantic understanding capabilities as possible, particularly for the contextual texts within the synthetic dataset. The motivation stems from the observation that while powerful models are highly effective, their large size can make them prohibitively expensive and slow for large-scale, low-latency applications. The student models are:</p><ul><li><a href="https://huggingface.co/altaidevorg/bge-m3-distill-8l">altaidevorg/bge-m3-distill-8l</a> (8-layer distilled model)</li><li><a href="https://huggingface.co/altaidevorg/bge-m3-distill-6l">altaidevorg/bge-m3-distill-6l</a> (6-layer distilled model)</li><li><a href="https://huggingface.co/altaidevorg/bge-m3-distill-4l">altaidevorg/bge-m3-distill-4l</a> (4-layer distilled model)</li></ul><p>The student models were derived from the BAAI/bge-m3 teacher model by <strong>reducing the number of model layers</strong>. This is a common and effective approach to creating smaller versions of transformer-based models.</p><p><strong>Architecture:</strong> Transformer encoder with 4, 6, and 8 layers respectively for altaidevorg/bge-m3-distill-4l, altaidevorg/bge-m3-distill-6l, and altaidevorg/bge-m3-distill-8l. The 8-layer model (altaidevorg/bge-m3-distill-8l), for example, has a 366 million parameter size, a significant reduction from the original 24-layer teacher. Other architectural parameters (e.g., hidden size, number of attention heads) are typically kept consistent with the layer configuration of the teacher model or scaled appropriately to maintain architectural integrity while reducing depth.</p><p><strong>Training Data:</strong><br>Distillation used a mix of general text corpora and domain-specific contextual texts from the synthetic dataset (including question-answer pairs). This combination aimed to ensure both general understanding and adaptation to the target domain.</p><p><strong>Use Cases:</strong></p><p>These models are intended for:</p><ul><li>Semantic search</li><li>Information retrieval</li><li>Document clustering</li><li>As embedding components in Retrieval-Augmented Generation (RAG) systems, especially for contextual texts in the synthetic dataset.</li></ul><p><strong>Performance:</strong><br> Performance was measured using Precision@k and improvements in inference speed and size. For example, the 8-layer model processed about 454 texts/sec on a T4 GPU, 2.5× faster than the teacher model (175 texts/sec). It also showed strong alignment with the teacher’s output, scoring a Spearman Cosine of 0.965 and MSE of 0.006 on the test set.</p><p><strong>Limitations:</strong></p><ul><li>May lose some depth on complex tasks compared to the full teacher model.</li><li>Might generalize less effectively to unrelated domains or unsupported languages.</li><li>Could inherit biases from the teacher model or training data.</li></ul><h3><strong>3. Experimental Setup</strong></h3><p>To evaluate the performance of the distilled models, a robust experimental setup was designed, focusing on a semantic search task using a synthetic dataset composed of contextual texts and synthetically generated questions. The primary aim of this evaluation is to understand how the retrieval behavior of the distilled models compared to each other.</p><p><strong>3.1 Dataset and Vector Search Process</strong></p><p>The dataset used in the evaluation process of distilled models is a set of synthetically generated questions derived from contextual texts within the synthetic dataset. Each query in this dataset is converted into a high-dimensional vector representation that captures its semantic meaning. This embedding is then used to search against the pre-indexed document embeddings in the <strong>Qdrant vector database</strong>. The system retrieves the top-<em>k</em> most semantically similar document IDs from the collection, where <em>k</em> is varied across multiple evaluation rounds (e.g., 10, 20, 30, 40, 50) . This process is repeated for each student model to allow for consistent and comparative evaluation.</p><p><strong>3.2 Evaluation Metric: Precision@k</strong></p><p>Precision@k is a widely used evaluation metric in information retrieval to measure the proportion of <strong>overlapping items found within the top k results returned by two different systems</strong> (or models) for the same query. When comparing two models, Model A and Model B, the formula for Precision@k is:</p><blockquote>P@k A vs. B = |{Model A’s top-k retrieved docs} ∩ {Model B’s top-k retrieved docs}| / k</blockquote><p>Where:</p><ul><li><strong>|{Model A’s top-k retrieved docs} ∩ {Model B’s top-k retrieved docs}| </strong>is the number of documents common to both Model A’s and Model B’s top k retrieved sets for a given query.</li><li><strong>k</strong> is the number of top results considered.</li></ul><p>In this experimental context, Precision@k is used to compare the student models against each other (e.g., 4L vs. 6L, 4L vs. 8L, 6L vs. 8L) for k values of <strong>10, 20, 30, 40, and 50</strong>. This range allows for analyzing not just how the models align on the most highly ranked results (small k), but also how much overlap exists as the retrieval scope broadens (larger k).</p><p>By examining Precision@k across different values of k, the evaluation uncovers how <strong>model depth impacts retrieval similarity</strong>, giving insight into <strong>trade-offs between architectural simplicity and semantic alignment</strong>.</p><h3><strong>4. Results</strong></h3><p>The distilled models were evaluated based on their retrieval performance (Precision@k scores) when compared to each other.</p><p><strong>4.1 Performance (Precision@k Scores)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100c0f59734b44cb513345dfe3c5f32b/href">https://medium.com/media/100c0f59734b44cb513345dfe3c5f32b/href</a></iframe><h3><strong>Observations:</strong></h3><ul><li>The <strong>altaidevorg/bge-m3-distill-6l</strong> and <strong>altaidevorg/bge-m3-distill-8l</strong> models exhibit the highest similarity in their retrieval behavior across all tested values of <em>k</em>. Precision@k (P@k) scores between these two models range from <strong>0.700 at k=10</strong> to <strong>0.792 at k=50</strong>, indicating that their top retrieved documents are largely overlapping. This suggests that, despite having fewer layers, the 6-layer model closely mirrors the retrieval patterns of the more expressive 8-layer variant.</li><li>In contrast, the <strong>altaidevorg/bge-m3-distill-4l</strong> model shows noticeably lower alignment with both the 6L and 8L models. For example, the P@10 score between the 4L and 8L models is <strong>0.580</strong>, which gradually increases to <strong>0.665 at P@50</strong>. This indicates that the 4-layer model diverges more in selecting the most relevant documents, particularly in the top-ranked results.</li><li>A broader trend observed across all inter-model comparisons is that <strong>P@k values generally increase or stabilize as <em>k</em> increases</strong>. This means that while the most highly ranked results (e.g., top 10) may vary more between models — especially between those with greater architectural differences like 4L vs. 8L — the overlap in retrieved documents grows when a larger set of top results (e.g., top 50) is considered. This implies that although models may differ in how they prioritize the most relevant documents, they still tend to agree on the broader set of documents considered relevant to a query.</li></ul><blockquote><strong>Efficiency Gains:</strong> A significant aspect of these distilled models is their efficiency. The altaidevorg/bge-m3-distill-8l model, for example, provides an empirically measured inference speedup of approximately 2.5x compared to the original 24-layer BAAI/bge-m3 teacher model, alongside substantial reductions in model size (366m parameters). The 6L and 4L variants are projected to offer even greater efficiency, with estimated speedups of approximately 3.1x and 4.0x respectively, compared to the original 24-layer teacher model. These estimations are based on the layer reduction and the observed performance of the 8L model.</blockquote><h3><strong>Conclusion</strong></h3><p>This study on distilling the <strong>BAAI/bge-m3</strong> model has resulted in the development of a series of more lightweight and computationally efficient embedding models: <strong>altaidevorg/bge-m3-distill-8l</strong>, <strong>altaidevorg/bge-m3-distill-6l</strong>, and <strong>altaidevorg/bge-m3-distill-4l</strong>. These distilled variants were designed to strike a balance between semantic performance and practical deployment needs such as speed and resource efficiency.</p><p>The comparative evaluation — particularly through <strong>Precision@k (P@k)</strong> metrics — highlights the nuanced trade-offs between model size, inference speed, and retrieval fidelity. The <strong>8-layer model</strong> emerges as a robust baseline, offering a <strong>2.5× speedup</strong> over the original 24-layer teacher model with minimal loss in retrieval quality. It serves as a strong default option for most retrieval-based applications.</p><p>The <strong>6-layer model</strong> demonstrates impressive alignment with the 8-layer variant, achieving a <strong>P@50 of 0.792</strong>, indicating that it preserves much of the retrieval behavior while being even more resource-efficient. This makes it an attractive choice for environments where performance needs to be balanced with greater throughput or tighter latency constraints.</p><p>The <strong>4-layer model</strong>, while understandably showing the largest deviation in top-k retrieval overlap (e.g., <strong>P@10 of 0.580</strong> compared to the 8-layer model), offers the <strong>highest projected speedup of approximately 4.0×</strong>. Its lightweight architecture makes it especially well-suited for use cases where <strong>maximizing inference speed and minimizing computational footprint</strong> are paramount, even at the cost of some retrieval precision.</p><p>Together, these models provide a flexible set of options for embedding-based applications, enabling practitioners to make informed decisions based on their specific trade-off requirements between speed, scale, and retrieval fidelity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9430e21c6b8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/altai-dev/distilling-efficiency-experiments-in-compressing-baai-bge-m3-using-a-synthetic-dataset-9430e21c6b8f">Distilling Efficiency: Experiments in Compressing BAAI/bge-m3 using a Synthetic Dataset</a> was originally published in <a href="https://medium.com/altai-dev">Altai.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Pose Estimation with MediaPipe]]></title>
            <link>https://medium.com/@aleynaahukmet/human-pose-estimation-with-mediapipe-805de21da9f1?source=rss-af1209f5ccc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/805de21da9f1</guid>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[gym-tracker]]></category>
            <category><![CDATA[pose-estimation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Aleynaahukmet]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 18:43:15 GMT</pubDate>
            <atom:updated>2022-04-11T18:43:15.597Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Human Pose Estimation?</strong></p><p>Human Pose Estimation (HPE) is a way of identifying and classifying the joints in the human body. Essentially it is a way to capture a set of coordinates for each joint (arm, head, torso, etc.,) which is known as a key-point that can describe a pose of a person. The connection between these points is known as a pair.</p><p>Humans fall into a particular category of objects that are flexible. By bending our arms or legs, key-points will be in different positions relative to others. Most inanimate objects are rigid. For instance, the corners of a brick are always the same distance apart regardless of the brick’s orientation. Predicting the position of these objects is known as rigid pose estimation.</p><p>There’s also a key distinction to be made between 2D and 3D pose estimation. 2D pose estimation simply estimates the location of key-points in 2D space relative to an image or video frame. The model estimates an X and Y coordinate for each key-point. 3D pose estimation works to transform an object in a 2D image into a 3D object by adding a z-dimension to the prediction.</p><p>3D pose estimation allows us to predict the actual spatial positioning of a depicted person or object. As you might expect, 3D pose estimation is a more challenging problem for machine learners, given the complexity required in creating datasets and algorithms that take into account a variety of factors — such as an image’s or video’s background scene, lighting conditions, and more.</p><p>Finally, there is a distinction between detecting one or multiple objects in an image or video. These two approaches can be referred to as single and multi pose estimation, and are largely self-explanatory: Single pose estimation approaches detect and track one person or object, while multi pose estimation approaches detect and track multiple people or objects.</p><p>There are three types of approaches to model the human body:</p><ol><li><strong>Skeleton-Based Model:</strong> It is a skeletal-based model that represents the human body. Kinematic model, also called skeleton-based model, is used for 2D pose estimation as well as 3D pose estimation.</li><li><strong>Contour-Based Model:</strong> The contour model is a contour-based model that represents the human body shape using a contour around the human body. Planar model, or contour-based model is used for 2D pose estimation.</li><li><strong>Volume-Based Model:</strong> The volumetric model creates the three-dimensional mesh of a human and represents the shape and appearance of the human body. Planar model, or contour-based model is used for 2D pose estimation. Volumetric model, which is used for 3D pose estimation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*tU67K7JcdnRaMw557ux2Fw.png" /></figure><p><strong>Primary Techniques for Pose Estimation</strong></p><p>In general, deep learning architectures suitable for pose estimation are based on variations of convolutional neural networks (CNNs). Deep learning-based approaches are well defined by their ability to generalize any function (if a sufficient number of nodes are present in the given hidden layer). When it comes to computer vision tasks, deep convolutional neural networks (CNN) surpass all other algorithms, and this is true in HPE as well.</p><p>There are two overarching approaches: a <strong>bottom-up</strong> approach, and a <strong>top-down</strong> approach.</p><ol><li><strong>Top-down:</strong> Localize the humans -the network first uses an object detector to draw a box around each instance of an object- in the image or video and then estimates the key points followed by calculating the pose.</li><li><strong>Bottom-up: </strong>The model detects every instance of a particular key point (e.g. all left hands) in a given image and then attempts to assemble groups of keypoints into skeletons for distinct objects.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*GGEgisuv0tcaCRF6ux1_Eg.png" /></figure><p><strong>MediaPipe</strong></p><p>There are many other algorithms and open-source models for human pose estimation projects. But in this blog post, I will be implementing code for human pose estimation with MediaPipe. MediaPipe is an open-source framework from Google for building multimodal (eg. video, audio, any time series data), cross-platform (i.e Android, iOS, web, edge devices) applied ML pipelines. You can read more about MediaPipe <a href="https://mediapipe.dev/">here.</a></p><p>Now MediaPipe’s Pose detection is a State of the Art solution for high-fidelity <em>(i.e. high quality</em>) and low latency (<em>i.e. Damn fast</em>) for detecting <strong>33</strong> 3D landmarks on a person in real-time video feeds on low-end devices i.e. phones, laptops, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*piHeDSCFgq2pNd2mFYBNoA.png" /></figure><p>They are actually using a very successful deep learning recipe that is creating a 2 step detector, where you combine a computationally expensive object detector with a lightweight object tracker. You run the detector in the first frame of the video to localize the person and provide a bounding box around it, after that the tracker takes over and it predicts the landmark points inside that bounding box ROI, the tracker continues to run on any subsequent frames in the video using the previous frame’s ROI and only calls the detection model again when it fails to track the person with high confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*3X0KtbGJPZrJsooRejjS5g.png" /></figure><p>This model works best if the person is standing 2–4 meters away from the camera and one major limitation of their model is that this approach only works for single-person pose detection, it’s not applicable for multi-person detection.</p><h3><strong>Push-ups Tracker</strong></h3><p>In this part I will implement code for push ups tracking. Now let’s start!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92e62a396a42866638ef107f5928a2a9/href">https://medium.com/media/92e62a396a42866638ef107f5928a2a9/href</a></iframe><p>After we imported libraries then we will access two submodules. This our very first step begins <strong>which is to initialize our pose detection model</strong>, we will initialize the pose class using the <strong>mp.solutions.pose</strong> syntax. And then we will initialize mediapipe drawing class with<strong>mp.solutions.drawing_utils </strong>syntax. drawing_utils class will draw the landmarks points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8862fcba97f79b9ce28f11983ec3e92d/href">https://medium.com/media/8862fcba97f79b9ce28f11983ec3e92d/href</a></iframe><p>Now first we load our video. And then as we stored the instance of pose detection class mp_pose variable now we will use this variable to call the Pose method as <strong>mp_pose.Pose()</strong>and store it in pose variable. In this way we will set the function for pose estimation. After that I set a counter variable which will help us count the numbers of our push-ups later. And we set another variable named stage to false for the same counter purpose which you will understand later on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e94140c7511dbc503c13760d808c688/href">https://medium.com/media/1e94140c7511dbc503c13760d808c688/href</a></iframe><p>Then we are starting a while loop. We are reading the video we captured frame by frame. After that we resize the image because our video was too big. And we convert image format to RGB because mediapipe requires RGB. We are accessing our pose model we set up earlier. At the next part we are using our pose model we set up earlier to detect poses. We pass our image, by processing it we’re going to get our detections back. Then we are storing our result in an array. Then we recolor it back to BGR for open-cv.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f858892f30ca837646336e5d7a0663c5/href">https://medium.com/media/f858892f30ca837646336e5d7a0663c5/href</a></iframe><p>Now we are creating a function for angle calculation. We pass through a,b,c parameters. In this project we are working on a push-ups tracking project so we wanted to calculate the shoulder angle. As first point (a), we can think it as shoulder. Middle point(b) is elbow and end point ( c) is wrist. So, at the function below calculates the angle between three points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8135fbd9e351363940b2fe46ae510208/href">https://medium.com/media/8135fbd9e351363940b2fe46ae510208/href</a></iframe><p>Then we store our detected our landmarks from result in landmarks variable with <strong>pose_landmarks.landmark</strong>. After that we get the x and y coordinates of shoulder, elbow and wrist points. And we use calculate_angle function to calculate the angle of these three points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/576102989020a7dcb1c38087b0fadadd/href">https://medium.com/media/576102989020a7dcb1c38087b0fadadd/href</a></iframe><p>In the next part we are getting height and width of image. So the coordinates we saw earlier, they were the normally scaled down to 0to 1. So they are not the coordinates based on the size of our particular image.We have to rescale them back to their original value by multiplying it by the width or the height of our image depending on their axis. Now we using putText method from cv2. And we are passing through different arguments.We are passing through our image. Then we are passing through the angle we calculated and converting it to string. And then we are determining where our positioning actually is. So the angle going to be positioned right next to our elbow. And then we are multiplying it by the dimensions of our video. Because cv2 requires these values to be integers we’re converting it to integer.<br>And then we are converting it to tuple because that is what cv2 to expects.<br>Then we are passing through the font we want and the size of the font,color of the font,thickness of the line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/755bb87a4cc5b39e949ae07c490ac929/href">https://medium.com/media/755bb87a4cc5b39e949ae07c490ac929/href</a></iframe><p>At the first part we are setting up whether or not we are at the down position.This is where the variables (counter, stage) we set earlier comes to picture. So if our angle or greater than 90 we are basically saying we are at the up position and we are setting the stage to ‘up’. At the next part we are saying if our angle is at 90 or less than 90 and stage is set to up then what we are doing is actually reseting our stage and setting it to down position.<br>And we will increase the counter to 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6373dc3f0a3d7265bc7e145e8972b839/href">https://medium.com/media/6373dc3f0a3d7265bc7e145e8972b839/href</a></iframe><p>we want to show a status rectangle on the screen which will show the number of push-ups. We pass trough the image, start point of our rectangle, end point of our rectangle,and color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05b35c062327183bbeb2707ee7ab4a62/href">https://medium.com/media/05b35c062327183bbeb2707ee7ab4a62/href</a></iframe><p>And here is a picture of our output. As you can see below there is a tracker box on the left-top which counts the number of push-ups and we can also see the angle and landmarks on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6TILOSMiGfedGWUVd6cyQ.png" /></figure><p><strong>References</strong></p><ul><li><a href="https://medium.com/nerd-for-tech/deep-learning-based-human-pose-estimation-using-opencv-and-mediapipe-d0be7a834076">Deep Learning based Human Pose Estimation using OpenCV and MediaPipe</a></li><li><a href="https://medium.com/augmented-startups/pose-estimation-in-7-minutes-30-fps-on-cpu-tutorial-c8d5ff35a21f">Pose Estimation in 7 Minutes — 30 fps on CPU Tutorial</a></li><li><a href="https://towardsdatascience.com/human-pose-estimation-simplified-6cfd88542ab3">Human Pose Estimation : Simplified</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=805de21da9f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection with YOLO v3]]></title>
            <link>https://medium.com/@aleynaahukmet/object-detection-with-yolo-v3-6f16ffb61701?source=rss-af1209f5ccc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f16ffb61701</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[yolov3]]></category>
            <dc:creator><![CDATA[Aleynaahukmet]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 16:21:36 GMT</pubDate>
            <atom:updated>2022-03-29T16:21:36.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Object detection is a significant part of computer vision. Object detection aids in pose estimation, vehicle detection, surveillance, etc. The difference between object detection algorithms and classification algorithms is that in detection algorithms, we try to draw a bounding box around the object of interest to locate it within the image. Also, you might not necessarily draw just one bounding box in an object detection case, there could be many bounding boxes representing different objects of interest within the image and you would not know how many beforehand. There are many different models like R-CNN, Fast R-CNN , Faster R-CNN , YOLO, etc. to approach object detection problems. But in this paper, we will be talking about YOLO.</p><p>Because YOLO is one of the fastest real-time object detection algorithms (45 frames per second) as compared to the R-CNN family. The R-CNN family of algorithms uses regions to localize the objects in images which means the model is applied to multiple regions and high scoring regions of the image are considered as object detected. But YOLO follows a completely different approach. Instead of selecting some regions, it applies a neural network to the entire image to predict bounding boxes and their probabilities.</p><p>What are the advantages of YOLO algorithm?</p><ul><li><strong>Speed:</strong> This algorithm improves the speed (45 fps) of detection because it can predict objects in real-time.</li><li><strong>High accuracy: </strong>YOLO is a predictive technique that provides accurate results with minimal background errors.</li><li><strong>Learning capabilities: </strong>The algorithm has excellent learning capabilities that enable it to learn the representations of objects and apply them in object detection.</li></ul><h3><strong>How Does YOLO Work?</strong></h3><p>I will not give deep dive into the architecture behind YOLO models but let’s briefly talk about the YOLO framework. YOLO algorithm works using the following three techniques:</p><ul><li>Residual blocks</li><li>Bounding box regression</li><li>Intersection Over Union (IOU)</li></ul><p><strong>Residual Blocks</strong></p><p>First, the image is divided into various grids. Each grid has a dimension of S x S. The following image shows how an input image is divided into grids. There will be many grid cells of equal dimensions. Every grid cell will detect objects that appear within them. For example, if an object center appears within a certain grid cell, then this cell will be responsible for detecting it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*uNHmEzeVquFuDzqpMymMJw.png" /><figcaption>SxS grid</figcaption></figure><h4>Bounding Box Regression</h4><p>A bounding box is an outline that highlights an object in an image. Every bounding box in the image consists of the following attributes:</p><ul><li>Bounding box center (bx,by)</li><li>Width (bw)</li><li>Height (bh)</li><li>Class (for example, person, car, traffic light, etc.)- This is represented by the letter c.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*7KJQVGIyiRpTFPyqURrZRA.jpeg" /></figure><p>YOLO uses a single bounding box regression to predict the height, width, center, and class of objects. In the image above, pc represents the probability of an object appearing in the bounding box.</p><h4>Intersection over Union (IOU)</h4><p>Intersection over Union (IOU) is a phenomenon in object detection that describes how boxes overlap. YOLO uses IOU to provide an output box that surrounds the objects perfectly.</p><p>Each grid cell is responsible for predicting the bounding boxes and their confidence scores. The IOU is equal to 1 if the predicted bounding box is the same as the real box. This mechanism eliminates bounding boxes that are not equal to the real box.</p><p>The following image provides a simple example of how IOU works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvLpxf2024-Vez5s30dSrw.png" /></figure><p>If IoU is greater than 0.5, we can say that the prediction is good enough. 0.5 is an arbitrary threshold we have taken here, but it can be changed according to your specific problem. Intuitively, the more you increase the threshold, the better the predictions become.</p><p>There is one more technique that can improve the output of YOLO significantly — Non-Max Suppression. One of the most common problems with object detection algorithms is that rather than detecting an object just once, they might detect it multiple times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFMbyYd2SQVBAj3IXlNLlQ.png" /></figure><p>We are taking the boxes with maximum probability and suppressing the close-by boxes with non-max probabilities. So long story short is:</p><ol><li>Discard all the boxes having probabilities less than or equal to a pre-defined threshold (say, 0.5)</li><li>For the remaining boxes, pick the box with the highest probability and take that as the output prediction. And discard any other box which has IoU greater than the threshold with the output box from the above step.</li><li>Repeat step 2 until all the boxes are either taken as the output prediction or discarded.</li></ol><p>So, image below explains the steps we mentioned visually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*PfnvTq7q3uT7DUtOR8mmLg.png" /></figure><h3>Implementing YOLO in Python</h3><p>We’ll be using YOLOv3 in this blog post, in particular, YOLO trained on the COCO dataset. The COCO dataset consists of 80 labels. Beside coco.names file we will also need weights and configuration files.</p><p>You can download the configuration file (yolov3.cfg) file from this <a href="https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg">link</a>.</p><p>You can download coco.names (80 classes names) file from this <a href="https://github.com/pjreddie/darknet/blob/master/data/coco.names">link</a><strong>.</strong></p><p>You can download pre-trained weights (yolo.weights) file from this <a href="https://pjreddie.com/media/files/yolov3.weights">link</a>.</p><p>Let’s begin coding:</p><p>First, we need to import OpenCV and NumPy libraries. Then we load the YOLO v3 algorithm using cv2.dnn.readNet by passing weights and configuration files. Then we will load all classes names in an array using coco.names file. N,ext we will define output layers because that’s where we will be defining what object is detected by using <strong>net.getUnconnectedOutLayers</strong> and <strong>net.getLayerNames</strong>. And we initialized label colors to color our bounding boxes and set a font type for our class names.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9558707ccedd761befac3168eae6efee/href">https://medium.com/media/9558707ccedd761befac3168eae6efee/href</a></iframe><p>Now we load capture video from webcam. Then we load all frames of the video running in a while loop and store each frame using <strong>cap.read</strong> and perform operation of what we did for each image in the last article. If the cam object is returning something then the ret will be True. We will extract the image height and widths and channels of each frame in <strong>height, width, channels. </strong>Then we will create a 4-dimensional blob. You can read about how blobFromImage works <a href="https://pyimagesearch.com/2017/11/06/deep-learning-opencvs-blobfromimage-works/">here</a>. But to explain it shortly, let’s examine <strong>blobFromImage</strong> function:</p><p><strong>blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size, mean, swapRB=True, crop=False)</strong></p><p>In this project, we are taking 1/255.0 (0.00392) as a scale factor to scale our images. (416, 416) will be the size of our images because that isa standard size for YOLO v3. We are not going to have mean subtraction so it is (0,0,0). We set swapRB to True because OpenCV assumes images are in BGR channel order; however, we are using RGB order. To resolve this discrepancy we can swap the R and B channels in ‘image’ by setting this value to `True`. We also set crop to False because we do not want to crop our images.</p><p>After we create a blob then we give this blob as input to the net using <strong>net.setInput </strong>and then we get outputs from output layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abe6843dfb69e10f61e8d675eaab747a/href">https://medium.com/media/abe6843dfb69e10f61e8d675eaab747a/href</a></iframe><p>Mainly we will be trying to predict the confidence meaning how confident the algorithm is when it predicts some object. For this, we will loop through <strong>outs, </strong>first get all the <strong>scores </strong>for each <strong>out in outs</strong>. And then we loop through outs for detection. There are 85 points in the detection array. The first four indices are for coordinates of the box and indexes starting from 5 to 85 are for class confidences. So we taking indexes starting from 5 to 85to get scores. Then get the <strong>class_id </strong>that has the highest score amongst them and then assign <strong>confidence </strong>to value of <strong>scores</strong> by passing <strong>class_id</strong>.</p><p>We will assign the confidence level threshold as 0.5. Anything above 0.5 should mean an object detected.</p><p>As we mentioned above indexes from the start to the 5th of the detection array are bounding box coordinates. We take these coordinates and scale the bounding box coordinates with the size of the actual image (width, height as we stored before) Now we have the x and y coordinates of the center of the box (<strong>center_x, center_y) and w</strong> as width, <strong>h </strong>as the height of the box detected.</p><p>Then we use center (center_x, center_y) coordinates to get the top left coordinates of bounding box. Then we update our lists (boxes, confidences, classIDs).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/367afa6c1bcc3147cc2037c99e1fac2f/href">https://medium.com/media/367afa6c1bcc3147cc2037c99e1fac2f/href</a></iframe><p>We already talk about Non-Maximum Suppression and why we need it in this blog. So it is time to code it. Now we have got all the bounding boxes, but we need only one bounding box for each object so we pass the bounding boxes to <strong>NMS</strong> function from OpenCV. Based on the confidence threshold and nms threshold the boxes will get suppressed and we will get box which detects the object correctly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc8bab5d2b8e5080e980c6dc8c015ae8/href">https://medium.com/media/bc8bab5d2b8e5080e980c6dc8c015ae8/href</a></iframe><p>Now using the below loop over all found <strong>boxes</strong>, if the box is appearing in <strong>indexes</strong> then only draw a rectangle, color it, and put the text of class name and confidence score on it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aad288748d8f384c4c8a529abdc51fa1/href">https://medium.com/media/aad288748d8f384c4c8a529abdc51fa1/href</a></iframe><p>Lastly, we show detected objects using cv2.imshow()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2b95cd0f5a68dcf203957cf9b4998ad/href">https://medium.com/media/a2b95cd0f5a68dcf203957cf9b4998ad/href</a></iframe><p>And this is the final result I get from the video I give to the algorithm as input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cdpJUJ9JoBb67Uze9nD4w.png" /></figure><p><strong>References</strong></p><ul><li><a href="https://amrokamal-47691.medium.com/yolo-yolov2-and-yolov3-all-you-want-to-know-7e3e92dc4899">YOLO, YOLOv2 and YOLOv3: All You want to know</a></li><li><a href="https://odsc.medium.com/overview-of-the-yolo-object-detection-algorithm-7b52a745d3e0">Overview of the YOLO Object Detection Algorithm</a></li><li><a href="https://towardsdatascience.com/review-yolov3-you-only-look-once-object-detection-eab75d7a1ba6">Review: YOLOv3 — You Only Look Once (Object Detection)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f16ffb61701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Region-Based CNN’ler ile Görüntü Segmentasyonu]]></title>
            <link>https://medium.com/@aleynaahukmet/region-based-cnnler-ile-g%C3%B6r%C3%BCnt%C3%BC-segmentasyonu-6c66a0a6c7b3?source=rss-af1209f5ccc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c66a0a6c7b3</guid>
            <category><![CDATA[r-cnn]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[mask-r-cnn]]></category>
            <category><![CDATA[faster-r-cnn]]></category>
            <category><![CDATA[fast-rcnn]]></category>
            <dc:creator><![CDATA[Aleynaahukmet]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 11:14:33 GMT</pubDate>
            <atom:updated>2022-02-25T11:14:33.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu yazıda görüntü segmentasyonu, R-CNN, Fast R-CNN hakkında kısa bilgiler verdikten sonra Faster R-CNN ve Mask R-CNN ile ilgili daha ayrıntılı olarak konuşacağız.</p><p>Evrişimli Sinir Ağları’nı (CNN’ler) sınıflandırmadan çok daha fazlası için kullanıyoruz. Sınıflandırmada, genellikle tek bir nesneye sahip bir görüntü vardır ve modelimiz bize bu nesnenin ne olduğunu kolaylıkla söyleyebilir. Ancak çevremize baktığımızda görmenin ve sınıflandırmanın karmaşıklığı tek bir nesne içeren görüntüleri sınıflandırmaktan çok daha karmaşıktır. Çok sayıda örtüşen nesne ve farklı arka planlara sahip karmaşık manzaralar görürüz ve bu farklı nesneleri yalnızca sınıflandırmakla kalmayıp aynı zamanda bunların sınırlarını, farklılıklarını ve nesnelerin birbirleri ile ilgili olan ilişkilerini de tanımlıyoruz. Peki insanların kolaylıkla gerçekleştirdiği bu görevleri makinelerin gerçekleştirmesinde CNN’ler bize nasıl yardımcı olabilir?</p><p>Bu yazıda öncelikle segmentasyon, R-CNN, Fast R-CNN hakkında kısa bilgiler verip daha ayrıntılı bir şekilde Faster R-CNN ve Mask R-CNN konularını ele alacağız.</p><h3><strong>Görüntü Segmentasyonu</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_fp-cREDdsEhPGadsgQWw.jpeg" /><figcaption>Kaynak: ResearhGate</figcaption></figure><p>Görüntü segmentasyonunu bir örnek üzerinden açıklamaya çalışalım. Yukarıda görselde verildiği gibi tek bir nesneden oluşan (kedi veya köpek gibi) görüntüleri kullanarak bir sınıflandırıcı modeli oluşturabilir ve görüntüde bir kedi olduğunu tahmin edebiliriz. Peki ya bir görüntüde hem kedimiz hem köpeğimiz hem de bir ördeğimiz olsaydı? Bu durumda bir çok etiketli sınıflandırıcı eğitebiliriz ancak görüntüdeki her bir nesnenin yerini bilemeyeceğiz.</p><p>Image localization (görüntü yerelleştirme) devreye burada girer. Verilen görüntüdeki tek bir nesnenin yerini belirlememize yardımcı olur. Birden fazla nesnemiz olması durumunda Object Detection(OD) kavramına güveniriz. OD kullanılarak her nesne için sınıfı ile birlikte konumunu da tahmin edebiliriz.</p><p>Nesneleri tespit etmeden ve görüntüyü sınıflandırmadan önce görüntünün nelerden oluştuğunu anlamamız gerekir. Burada devreye image segmentation girer.</p><p>Peki görüntü segmentasyonunun çalışma mantığı nedir?</p><p>Görüntüde herhangi bir bilgi içermeyen bölgeler olacağından tüm görüntüyü bir bütün halinde işlemek çok doğru bir fikir değildir. Görüntüyü segment adı verilen çeşitli parçalara böleriz. Görüntüyü bu parçalara ayırarak işlemek için daha önemli parçalardan yararlanabiliriz. Özetle segmentasyon böyle çalışır.</p><p>Bir görüntü farklı pikseller kümesidir. Görüntü segmentasyonu kullanarak benzer niteliklere sahip pikselleri gruplandırırız.</p><p>Yukarıda verilen görselde az çok nesne algılama ile segmentasyon arasında ki fark anlaşılmıştır. Object Detection (nesne algılama), görüntüde her sınıfa karşılık gelen bir bounding box (sınırlayıcı kutu) oluşturur. Ama bize nesnenin şekli hakkında pek bilgi vermez. Yalnızca sınırlayıcı kutu koordinatları kümesini alırız. Görüntü segmentasyonuna gelince görüntüdeki her nesne için piksel bazında bir maske oluşturur. Peki buna neden ihtiyacımız var?</p><p>Segmentasyona neden ihtiyaç olduğunu sağlık alanından bir örnek vererek açıklayalım. Çağımızın en büyük hastalıklarından biri kanserdir ve günümüz teknolojisinde bile geç teşhisi halinde ölümcül olabilir. Kanserli hücreleri mümkün olduğunca çabuk teşhis etmek milyonlarca hayat kurtarabilir. Kanserli hücrelerin şekli, kanserin seviyesinin ve türünün belirlenmesinde hayati bir rol oynar ve tahmin edildiği üzere nesne algılama bu konuda pek yardımcı olmayacaktır. Nesne algılama ile bu görüntüler üzerinde yalnızca hücrelerin çevresinde şekillerinin belirlenmesinde yardımcı olmayacak sınırlayıcı kutular oluşturacağız. Ancak segmentasyon ile durum tahmin ettiğiniz gibi çok daha farklı olacak. Aşağıdaki görsele bakılırsa kanserli hücrelerin şekillerini net bir şekilde görebiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*AGYgBl475HEZTQuPyGPZXw.png" /><figcaption>Kanserli Hücreler</figcaption></figure><p>Görüntü segmantasyonu hakkında genel olarak bir fikrimiz oluştuğuna göre iki farklı görüntü segmentasyonu hakkında bilgi vereceğim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*kBFzNFbBUmCvqAXenFnRjw.png" /><figcaption>Semantic and Instance Segmentasyonu</figcaption></figure><ul><li>Semantic Segmentation (image 1): Burada her piksel belirli bir sınıfa (arka plan veya nesne) aittir. Ayrıca, belirli bir sınıfa ait tüm pikseller aynı renkle temsil edilir (arka plan siyah ve kişiler pembe).</li><li>Instance Segmentation (image 2): Burada görüntünün her pikseline belirli bir sınıf atamıştır. Ancak aynı sınıfa ait farklı nesnelerin renkleri farklıdır (Kişi 1 kırmızı, Kişi 2 yeşil, arka plan siyah vb.).</li></ul><p>Öğrendiklerimizi kısaca özetleyelim. Diyelim ki bir görüntüde 5 kişi varsa, semantic segmentation bu 5 kişiyi tek bir örnek olarak sınıflandıracaktır. Öte yandan instance segmentation bu kişilerin her birini ayrı ayrı tanımlayacaktır.</p><p>Hadi şimdi R-CNN algoritmalarına bir giriş yapalım.</p><h3>R-CNN Algoritmalarının Kısa Bir Özeti</h3><p>R-CNN’nin amacı bir görüntüyü almak ve nesnelerin (sınırlayıcı kutu aracılığıyla) görüntüdeki yerini doğru bir şekilde belirlemektir. R-CNN, selective search (seçici arama) kullanarak verilen görüntüden bir grup bölge çıkarır ve ardından bu kutulardan herhangi birinin nesne içerip içermediğini kontrol eder. Selective search farklı boyutlardaki pencereler aracılığıyla görüntüye bakar ve her bir boyut için nesneleri tanımlamak adına bitişik pikselleri gruplandırmaya çalışır. Bu işlem sonucu teklifler oluşturulduktan sonra, R-CNN bölgeyi standart bir kare boyutuna çarpar ve aşağıda gösterildiği gibi CNN’e iletir. CNN’nin son katmanında, R-CNN bunun bir nesne olup olmadığını ve eğer öyleyse hangi nesne olduğunu basitçe sınıflandıran bir SVM ekler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*OdvipH1Mt5eKxI8B_zHCCA.png" /></figure><p>Faster R-CNN ile Mask R-CNN hakkında daha detaylı açıklamalar vermeden önce R-CNN algoritmalarının mantığını ve temellerini kısaca bir gözden geçireceğiz. R-CNN, selective search (seçici arama) kullanarak verilen görüntüden bir grup bölge çıkarır ve ardından bu kutulardan herhangi birinin nesne içerip içermediğini kontrol eder. Yani önce bu bölgeleri çıkarıyoruz ve her bölge için belirli özellikleri çıkarmak için CNN kullanıyoruz. Son olarak bu özellikler daha sonra nesneleri algılamak için kullanılır. Ne yazık ki, süreçte yer alan bu çoklu adımlar nedeniyle R-CNN oldukça yavaş çalışır.</p><h3><strong>Fast R-CNN</strong></h3><p>Fast R-CNN ise görüntünün tamamını (görüntüden çıkarılan bazı bölümler yerine) daha sonra region of interest (ilgi alanları) oluşturan ConvNet’e iletir. Ayrıca R-CNN’de olduğu gibi üç farklı model kullanmak yerine bölgelerden öznitelikleri çıkaran, bunları farklı sınıflara sınıflandıran ve sınırlayıcı kutuları döndüren tek bir model kullanır. Tüm bu işlemler aynı anda yürütülür bu sebeple R-CNN’ye kıyasla daha hızlıdır. Ancak Fast R-CNN de aynı şekilde seçici arama kullandığından büyük bir veri setine uygulandığı zaman yavaş çalışacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*LRpM5aR1fm_Z3_RhKhNHLQ.png" /><figcaption>Fast R-CNN</figcaption></figure><h3><strong>Faster R-CNN</strong></h3><p>R-CNN ve Fast R-CNN ile kısa bilgiler verdik ve şimdi Faster R-CNN daha popüler bir yöntem olduğu için bundan daha ayrıntılı bahsedeceğiz. Seçici arama algoritmasının Fast R-CNN’de yarattığı problemden zaten bahsetmiştik. Öte yandan Faster R-CNN seçici arama yerine Region Proposal Network (RPN) kullanarak bu sorunu çözer. İlk önce ConvNet kullanarak girdi görüntüsünden özellik haritaları çıkarılır ve ardından bu haritalar object proposals (nesne teklifleri) döndüren bir RPN’den geçirilir. Son olarak bu haritalar sınıflandırılır ve sınırlayıcı kutular tahmin edilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*7OX74HfYatQ1n-XiuIONNA.png" /><figcaption>Fater R-CNN</figcaption></figure><p>Kısaca Faster R-CNN algoritmasının adımları:</p><ol><li>Bir girdi görüntüsü alır ve görüntünün özellik haritalarını çıkaran ConvNet’e iletir.</li><li>Bu özellik haritalarına RPN uygulanır ve nesne teklifleri alınır.</li><li>Tüm teklifleri aynı boyuta getirmek için ROI pooling katmanı uygulanır.</li><li>Son olarak bu teklifleri bir fully-connected katmana besleriz ve çıktı olarak sınıflandırmalar ile sınırlayıcı kutu koordinatlarını alırız.</li></ol><p><strong>Region Proposal Network (RPN)</strong></p><p>RPN, görüntüyü kayan pencere biçiminde tarayan ve nesneleri içeren alanları bulan bir sinir ağıdır. RPN, yukarıda da belirttiğimiz gibi ConvNet’ten çıkan özellik haritaları üzerinde çalışır. RPN’nin taradığı bölgelere anchor (çapa) denir. Pratikte, farklı boyut ve en boy oranlarında 200K çapa vardır ve bunlar görüntünün mümkün olduğu kadar çoğunu kapsayacak şekilde üst üste gelir. RPN her bir çapa için iki çıktı verir:</p><ol><li>Anchor Class: İki tane class vardır: foreground (ön plan) background (arka plan) . Foreground sınıfı, o kutuda muhtemelen bir nesne olduğu ima eder.</li><li>Bounding Box Refinement: Bir foreground çapa (pozitif çapa olarak da adlandırılır) nesne üzerinde tam olarak ortalanmayabilir. Bu nedenle RPN, nesneye daha iyi uyması için çapa kutusunu hassaslaştırmak için bir delta (x, y, genişlik, yükseklikteki %’lik değişim) tahmin eder.</li></ol><p>RPN tahminlerini kullanarak, nesneleri içermesi en muhtemel çapaları seçiyor ve konumlarını ve boyutlarını iyileştiriyoruz. Birkaç çapa çok fazla örtüşürse, en yüksek ön plan puanına sahip olanı tutup geri kalanı atıyoruz. Bu aşamalardan sonra nihai tekliflere ( regions of interest) sahibiz.</p><p><strong>ROI Classifier &amp; Bounding Box Regressor</strong></p><p>Bu aşamada, RPN tarafından önerilen ilgi alanları (ROI’ler) üzerinde çalışılır ve RPN gibi her bir ROI için iki tane çıktı üretir:</p><ol><li>Class: ROI’deki nesnenin sınıfını verir. İki sınıfı olan RPN’den farklı olarak bu ağ daha derindir ve bölgeleri belirli sınıflara (kedi, köpek, ördek gibi.) göre sınıflandırma kapasitesine sahiptir. Ayrıca ROI’nin atılmasına neden olan bir arka plan sınıfı da olabilir.</li><li>Bounding Box Refinement: RPN’de nasıl yapıldığına benzer olarak, nesneyi sınırlamak için sınırlayıcı kutunun konumunu ve boyutunu daha da iyileştirmektir.</li></ol><p><strong>ROI Pooling</strong></p><p>RPN’deki sınırlayıcı kutu iyileştirme adımı nedeniyle, farklı boyutlarda önerilen ilgi alanları elde ederiz. İşte burada ROI pooling devreye giriyor. ROI pooling, özellik haritalarını aynı boyuta indirger. Sabit bir boyutu olan Max-Pooling’den farklı olarak, ROI pooling özellik haritasını kabaca eşit bölgelerden oluşan sabit bir sayıya (diyelim ki k) böler ve ardından her bölgeye Max-Pooling uygular.</p><h3><strong>Mask R-CNN</strong></h3><p>Mask R-CNN, temel olarak Faster R-CNN’nin bir uzantısıdır ve çerçevesi Faster R-CNN’nin üzerine inşa edilmiştir. Belirli bir görüntü için Mask R-CNN, her nesne için sınıf etiketine ve sınırlayıcı kutu koordinatlarına ek olarak, nesne maskesi de döndürür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*ZK3ctgIbYwPcYWjOcMEY7w.png" /></figure><p><strong>Backbone Model</strong></p><p>Görüntüden özellik haritaları çıkarmak için Faster R-CNN’de kullandığımız ConvNet’e benzer şekilde, Mask R-CNN’de görüntülerden özellikleri çıkarmak için ResNet mimarisi kullanılır. Bu nedenle bu modelde ilk adım ResNet mimarisini kullanarak görüntü almak ve özellikleri çıkarmaktır.</p><p><strong>Region Proposal Network (RPN)</strong></p><p>Aynı Faster R-CNN’de olduğu gibi bir önceki adımda elde edilen özellik haritalarını alıp bir RPN uygulanır. RPN yukarıda da açıkladığımız gibi temel olarak o bölgede bir nesnenin olup olmadığını tahmin eder.</p><p><strong>Region of Interest (RoI)</strong></p><p>RPN’den elde edilen bölgelere aynı boyutlar elde etmek için pooling katmanı uygulanır. Daha sonra bu bölgeler bir fully-connected katmandan geçirilir böylece sınıf etiketi ve sınırlayıcı kutular tahmin edilir. Bu noktaya kadar Faster R-CNN’nin çalışmasına benzer olduğunu farkettiniz mi? Faster R-CNN’den farklı olarak bunlara ek Mask R-CNN segmentasyon maskesi de oluşturur. Tahmin edilen tüm bölgeler için IoU diye bir değer hesaplanır.</p><blockquote>IoU = kesişme bölgeleri / birleşme bölgeleri</blockquote><p>Eğer IoU 0,5&#39;ten büyük veya 0,5&#39;e eşitse, bunu bir ilgi alanı(region of interest) olarak kabul ederiz. Aksi takdirde o bölgeyi ihmal ederiz. Bunu tüm bölgeler için yaparız ve sonucunda yalnızca IoU’nun 0,5&#39;ten büyük olduğu bir dizi bölge seçeriz. Aşağıdaki görselde bu kavram daha iyi anlaşılabilir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*QxYQOQzggDAf_AWIkRERWA.png" /></figure><p><strong>RoiAlign</strong></p><p>Faster R-CNN mimarisinde değişiklik yapılmadan çalıştırıldığında RoI pooling tarafından seçilen özellik haritası bölgelerinin orjinal görüntünün bölgelerinden biraz yanlış hizalandığı fark edildi. Görüntü segmentasyonu, sınırlayıcı kutulardan farklı olarak piksel düzeyinde bir bölütleme gerektirdiğinden bu durum büyük yanlışlıklara yol açar. Mask R-CNN’de RoI pooling yerinde RoIAlign olarak bilinen çift doğrusal enterpolasyon kullanılan bir yöntem ile daha hassas hizalanma sağlanmıştır. Bununla ilgili daha ayrıntılı bilgiye <a href="https://towardsdatascience.com/understanding-region-of-interest-part-2-roi-align-and-roi-warp-f795196fc193">buradan</a> ulaşabilirsiniz.</p><p><strong>Segmentation Mask</strong></p><p>IoU değerlerine dayalı RoI’lere sahip olduğumuzda mevcut mimariye bir maske dalı ekleyebiliriz. Bu, bir nesne içeren her bir bölge için segmentasyon maskesini döndürür. Görüntüde ki tüm nesneler için maskeleri tahmin ettiğimiz bu adım Mask R-CNN’deki son adımdır. Mask R-CNN için COCO veri setinde eğitilmiş Mask R-CNN modelinin önceden eğitilmiş ağırlıklarını kullanırız.</p><p>Kaynaklar:</p><ul><li><a href="https://analyticsindiamag.com/r-cnn-vs-fast-r-cnn-vs-faster-r-cnn-a-comparative-guide/">R-CNN vs Fast R-CNN vs Faster R-CNN - A Comparative Guide</a></li><li><a href="https://www.alegion.com/faster-r-cnn">Faster R-CNN</a></li><li><a href="https://jonathan-hui.medium.com/what-do-we-learn-from-region-based-object-detectors-faster-r-cnn-r-fcn-fpn-7e354377a7c9">What do we learn from region based object detectors (Faster R-CNN, R-FCN, FPN)?</a></li><li><a href="https://blog.athelas.com/a-brief-history-of-cnns-in-image-segmentation-from-r-cnn-to-mask-r-cnn-34ea83205de4">A Brief History of CNNs in Image Segmentation: From R-CNN to Mask R-CNN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c66a0a6c7b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>