<?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 Vidhi Singhal on Medium]]></title>
        <description><![CDATA[Stories by Vidhi Singhal on Medium]]></description>
        <link>https://medium.com/@isvidhi?source=rss-a40f1ee45706------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eb_dzv65x7HhRmvN1JJM7g.png</url>
            <title>Stories by Vidhi Singhal on Medium</title>
            <link>https://medium.com/@isvidhi?source=rss-a40f1ee45706------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:52:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isvidhi/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[Master–Slave Architecture: The Deterministic Backbone of PLC Communication]]></title>
            <link>https://isvidhi.medium.com/master-slave-architecture-the-deterministic-backbone-of-plc-communication-d03d955b53f3?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03d955b53f3</guid>
            <category><![CDATA[modbus-tcp]]></category>
            <category><![CDATA[modbus]]></category>
            <category><![CDATA[master-slave-architecture]]></category>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 12:38:15 GMT</pubDate>
            <atom:updated>2026-02-12T12:38:15.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ux4orcXU4rtJtJP-3lSEg.png" /></figure><p>In collaboration with <a href="https://medium.com/u/dba1bd4888ce">Ronak Jain</a>.</p><p>Industrial automation systems do not run on randomness. They rely on structured, deterministic communication between controllers, sensors, drives, and supervisory systems. One of the most widely used and long-standing communication models in this environment is the <strong>master–slave architecture</strong>.</p><p>Although newer communication paradigms are gaining popularity, master–slave communication remains foundational in PLC-based systems. This article explores how the model works, why it became dominant, where it is still used today, and what engineers and software developers should understand about it.</p><h3>Understanding the Master–Slave Model</h3><p>At its core, master–slave communication is simple:</p><ul><li>One device is designated as the <strong>master</strong></li><li>All other devices act as <strong>slaves</strong></li><li>The master controls all communication</li></ul><p>Slaves never transmit data on their own. They only respond when explicitly requested by the master. Communication follows a strict <strong>request–response pattern</strong>.</p><p>This controlled structure provides one critical advantage in industrial environments: <strong>predictability</strong>.</p><p>In systems where timing affects safety, performance, and equipment life, predictable communication is not optional, it is essential.</p><h3>The Role of PLCs in Master–Slave Systems</h3><p>Programmable Logic Controllers (PLCs) are central to industrial automation. Within a master–slave architecture, a PLC can operate in two roles depending on system design.</p><h3>PLC as Master</h3><p>When acting as the master, a PLC:</p><ul><li>Polls sensors for measurements</li><li>Reads data from remote I/O modules</li><li>Communicates with drives and actuators</li><li>Requests status information from other controllers</li></ul><p>In this configuration, the PLC initiates every communication cycle.</p><h3>PLC as Slave</h3><p>In other cases, a PLC functions as a slave. For example:</p><ul><li>A SCADA server may poll the PLC for process values</li><li>An industrial PC may send commands to the PLC</li><li>A supervisory controller may coordinate multiple PLCs</li></ul><p>In many industrial systems, multiple PLCs are connected together, with one serving as the master and others configured as slaves for structured data exchange.</p><h3>How Communication Actually Flows</h3><p>The communication cycle in a master–slave system follows a fixed sequence:</p><ol><li>The master sends a request to a specific slave</li><li>The addressed slave processes the request</li><li>The slave sends a response with data or status information</li><li>The master proceeds to the next slave</li></ol><p>This process repeats continuously based on a defined scan rate or communication schedule.</p><p>Because only one device transmits at a time, network collisions are avoided. This is especially important in serial communication environments such as <strong>RS-232 and RS-485</strong>, where unmanaged communication could result in data corruption.</p><p>The result is a clean, orderly data exchange cycle.</p><h3>Industrial Protocols Built on Master–Slave Architecture</h3><p>Several widely adopted industrial protocols are based on the master–slave model, including:</p><ul><li><strong>Modbus RTU</strong></li><li><strong>Modbus TCP</strong></li><li><strong>PROFIBUS DP (classic implementations)</strong></li><li><strong>DF1 (Allen-Bradley)</strong></li><li><strong>AS-Interface (AS-i)</strong></li></ul><p>While newer documentation increasingly uses the term <em>client–server</em>, the underlying communication behavior remains fundamentally the same: one device initiates, others respond.</p><h3>Determinism: The Real Advantage</h3><p>The most important strength of master–slave communication is <strong>determinism</strong>.</p><p>Since the master controls all communication timing, system designers can calculate:</p><ul><li>Network update rates</li><li>Maximum response times</li><li>Worst-case communication delays</li></ul><p>In control systems, this predictability directly impacts stability and safety. For example, if a PLC needs fresh sensor data every 50 milliseconds to maintain stable motor control, the communication architecture must guarantee that timing.</p><p>However, performance depends on several variables:</p><ul><li>Number of slave devices</li><li>Message size</li><li>Communication speed</li><li>Master scan rate</li></ul><p>As systems grow larger, the time required to poll each slave increases. Eventually, polling cycles can become a limiting factor.</p><h3>Why Master–Slave Became So Popular</h3><p>Master–slave architecture has endured for decades for several reasons.</p><h3>1. Simplicity of Implementation</h3><p>The model is conceptually straightforward and easy to implement in PLC firmware and embedded devices.</p><h3>2. Predictable Network Behavior</h3><p>Controlled communication eliminates random traffic and simplifies troubleshooting.</p><h3>3. Compatibility with Serial Networks</h3><p>The architecture works extremely well over serial links, where bandwidth is limited and collision avoidance is essential.</p><h3>4. Broad Vendor Support</h3><p>Because many vendors adopted this model early, it became a de facto industry standard. That compatibility remains valuable today.</p><p>In industrial automation, simplicity and stability often outweigh innovation.</p><h3>Limitations and Challenges</h3><p>Despite its strengths, master–slave communication is not perfect.</p><h3>Scalability</h3><p>As the number of slaves increases, the master must spend more time polling, which increases overall latency.</p><h3>Single Point of Control</h3><p>If the master fails, communication typically stops across the entire network.</p><h3>Limited Flexibility</h3><p>Slaves cannot initiate communication. In systems where data changes rapidly or events occur unpredictably, polling can be inefficient.</p><h3>Bandwidth Utilization</h3><p>Polling may request data even when values have not changed, leading to unnecessary network traffic.</p><p>These limitations have encouraged the development of more flexible communication models.</p><h3>Master–Slave vs. Modern Communication Models</h3><p>Modern industrial networks increasingly use architectures that support:</p><ul><li>Peer-to-peer communication</li><li>Event-driven messaging</li><li>Publish–subscribe mechanisms</li></ul><p>Examples include:</p><ul><li>Ethernet/IP (implicit messaging)</li><li>PROFINET IRT</li><li>OPC UA PubSub</li></ul><p>These models reduce latency, improve scalability, and better support complex distributed systems.</p><p>However, they also introduce additional complexity.</p><p>Master–slave communication remains attractive in environments where:</p><ul><li>Determinism is critical</li><li>Systems are relatively simple</li><li>Legacy equipment must be supported</li><li>Long-term stability is prioritized</li></ul><h3>How It’s Used in Modern Systems</h3><p>In practice, master–slave communication rarely exists in isolation. Instead, it is layered within broader architectures.</p><p>Common real-world patterns include:</p><ul><li>A PLC acting as master to field devices while exposing data upward to SCADA systems</li><li>Gateways translating master–slave protocols into MQTT or OPC UA</li><li>Hybrid networks where field-level communication uses master–slave, and higher-level networks use Ethernet-based protocols</li></ul><p>This layered approach allows decades-old infrastructure to coexist with modern analytics platforms and cloud systems.</p><h3>Why Understanding This Model Still Matters</h3><p>Even if future industrial systems move further toward distributed, event-driven architectures, master–slave communication will remain deeply embedded in field-level automation.</p><p>For engineers and software developers working with PLCs, understanding this model provides insight into:</p><ul><li>How timing affects control systems</li><li>Why deterministic communication matters</li><li>How legacy devices integrate with modern networks</li><li>Where bottlenecks may occur in scaling systems</li></ul><p>It is not just a historical concept—it is still operational reality.</p><p>Master–slave architecture remains a foundational communication model in PLC-based automation systems. Its deterministic behavior, simplicity, and compatibility with legacy equipment make it well-suited for many industrial applications.</p><p>While newer communication paradigms address scalability and flexibility challenges, master–slave communication continues to play a critical role at the field level of industrial systems.</p><p>For professionals working in industrial automation, understanding this architecture is not optional it is essential.</p><p>I would like to thank <a href="https://medium.com/u/dba1bd4888ce">Ronak Jain</a> for sharing foundational notes and technical insights on the Modbus protocol, which helped shape the direction and understanding of this article.</p><p>If you’d like to connect, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03d955b53f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modbus: A No-Nonsense Guide for Software Developers]]></title>
            <link>https://isvidhi.medium.com/modbus-a-no-nonsense-guide-for-software-developers-5baa9bfc96aa?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/5baa9bfc96aa</guid>
            <category><![CDATA[modbus-tcp]]></category>
            <category><![CDATA[modbus-gateway]]></category>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 15:26:51 GMT</pubDate>
            <atom:updated>2026-02-14T10:32:08.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c_Ini4mInmx-4k263O4gQ.png" /></figure><p>In collaboration with <a href="https://medium.com/u/dba1bd4888ce">Ronak Jain</a>.</p><p>If you’re a software developer stepping into industrial automation, one name will keep coming up: <strong>Modbus</strong>.</p><p>Modbus quietly runs <strong>factories, power plants, substations, and critical infrastructure</strong> across the world.</p><p>This article offers a practical introduction to Modbus what it is, why it still matters, how steep the learning curve really is, and where you’ll encounter it in real industrial automation systems.</p><h3>What Is Modbus?</h3><p>Modbus is an <strong>open, vendor-neutral communication protocol</strong> originally developed in 1979 by Modicon (now Schneider Electric). Its purpose is straightforward:<br><strong>to move data between industrial devices in a predictable and reliable way.</strong></p><p>Modbus defines how devices exchange raw data over serial connections or Ethernet networks. It doesn’t try to be clever or feature-rich. It focuses on doing one thing well <strong>reliable data transfer</strong>.</p><p>At its core, Modbus follows a <strong>request–response model</strong> (historically called master–slave, now client–server):</p><ol><li>A client initiates a request</li><li>A server responds with data or confirmation</li></ol><p>That’s it. No background messaging. No subscriptions. No discovery.</p><p>Importantly, Modbus intentionally avoids many things developers take for granted today. It does <strong>not</strong> handle authentication, device discovery, data schemas, or session management. Its scope is deliberately limited, which is exactly why it has survived for decades.</p><h3>Core Modbus Variants You’ll Actually See</h3><p>In theory, there are several Modbus variants. In practice, you’ll mostly encounter these three:</p><ul><li><strong>Modbus RTU</strong><br>Binary, compact, and efficient. Runs over serial lines like RS-485 or RS-232. Extremely common at the field level.</li><li><strong>Modbus ASCII</strong><br>Text-based and human-readable, but slower and largely legacy. You’ll see it occasionally, but rarely in new systems.</li><li><strong>Modbus TCP</strong><br>Modbus wrapped inside TCP/IP. Used on industrial Ethernet networks and common in modern control systems.</li></ul><p>For most software developers, <strong>Modbus TCP is the easiest entry point</strong>. Modbus RTU appears when you start interacting directly with hardware, sensors, and legacy field devices.</p><h3>The Purpose and Design Philosophy of Modbus</h3><p>Modbus was designed to solve one core problem:</p><p><strong>“How do we let devices from different manufacturers talk to each other without proprietary protocols?”</strong></p><p>The answer was interoperability through simplicity.</p><p>Key design goals include:</p><ul><li>Simple implementation</li><li>Deterministic behavior</li><li>Long-term stability</li><li>Minimal computational overhead</li></ul><p>These goals matter because industrial systems are very different from consumer software environments. Hardware often remains in service for <strong>20 to 40 years</strong>, vendors change, and downtime costs real money.</p><p>Modbus standardizes:</p><ul><li>How a device requests data</li><li>How registers are addressed</li><li>How values are encoded</li><li>How errors are reported</li></ul><p>It isn’t fancy but it’s predictable. And industry loves predictable.</p><h3>Why Modbus Is Still Relevant in 2026</h3><p>By modern software standards, Modbus should be obsolete. It isn’t and here’s why.</p><h3>1. Massive Installed Base</h3><p>Factories don’t rewrite protocols every five years. If a plant installed Modbus in the 1990s and it still works, it stays.</p><h3>2. Vendor Neutral and Open</h3><p>No licenses. No gatekeepers. Anyone can implement it, which keeps ecosystems flexible.</p><h3>3. Easy to Debug</h3><p>You can capture packets, read function codes, and inspect registers directly. That transparency is incredibly valuable during troubleshooting.</p><h3>4. Plays Well with Modern Tech</h3><p>Modbus rarely exists alone anymore. A common architecture looks like this:</p><p><strong>PLC (Modbus) → Gateway → MQTT / OPC UA → Cloud, SCADA, Analytics</strong></p><p>Modbus handles the low-level device communication while modern protocols manage higher-level data flow.</p><h3>Modbus Through a Software Developer’s Eyes</h3><p>If you come from web, backend, or mobile development, Modbus will feel uncomfortable at first.</p><p>There’s no:</p><ul><li>JSON</li><li>APIs</li><li>Authentication</li><li>Versioning</li><li>Service discovery</li></ul><p>Instead, you work with:</p><ul><li>Registers</li><li>Function codes</li><li>Fixed data sizes</li><li>Byte order issues</li></ul><p>It feels closer to <strong>bare-metal programming</strong> than application development — and that’s a mental shift many developers struggle with initially.</p><h3>Core Concepts You Must Understand</h3><h3>1. Registers (This Is Everything)</h3><p>All Modbus data lives in registers:</p><ul><li><strong>Coils</strong> — single-bit outputs (ON/OFF)</li><li><strong>Discrete Inputs</strong> — single-bit inputs</li><li><strong>Holding Registers</strong> — 16-bit read/write values</li><li><strong>Input Registers</strong> — 16-bit read-only values</li></ul><p>Everything temperature, pressure, speed, voltage eventually becomes one or more <strong>16-bit registers</strong>.</p><h3>2. Function Codes</h3><p>Function codes define what action you’re performing:</p><ul><li>Read holding registers</li><li>Write a single coil</li><li>Write multiple registers</li></ul><p>You don’t “call APIs.”<br>You <strong>issue function codes</strong> with specific addresses and data payloads.</p><h3>The Learning Curve (An Honest Take)</h3><p>Getting started with Modbus is relatively easy. Libraries exist for almost every programming language, and basic communication can often be implemented quickly.</p><p>What’s easy:</p><ul><li>Simple request/response model</li><li>Clear specification</li><li>Excellent library support</li></ul><p>What trips developers up:</p><ul><li>Endianness (byte order)</li><li>Signed vs unsigned values</li><li>Scaling factors (e.g., value × 0.1)</li><li>Vendor-specific register maps</li><li>Timing, retries, and timeouts</li><li>Serial line noise in RTU systems</li></ul><p>This is where many developers learn an uncomfortable truth:<br><strong>the protocol is simple, but real industrial devices are not.</strong> Success depends heavily on documentation and careful data interpretation.</p><h3>Typical Applications of Modbus in Industrial Automation</h3><h3>PLC Communication</h3><p>PLCs expose internal values via Modbus so other systems can monitor processes, adjust setpoints, and trigger actions.</p><h3>SCADA and HMI Systems</h3><p>SCADA software frequently uses Modbus to read live data, display alarms, visualize trends, and log historical information.</p><h3>Sensors and Actuators</h3><p>Common Modbus devices include temperature sensors, energy meters, flow meters, motor drives (VFDs), and power analyzers. These devices often communicate using Modbus RTU over RS-485.</p><h3>Why Software Developers Should Learn Modbus</h3><p>Modbus teaches things modern stacks hide:</p><ul><li>Deterministic communication</li><li>Byte-level data representation</li><li>Hardware constraints</li><li>Fault tolerance without abstractions</li></ul><p>Industrial automation moves slowly, pays well, and desperately needs developers who understand both software and physical systems. If you can bridge Modbus with modern platforms, you become useful immediately.</p><p>Modbus is a mature, well-established protocol that continues to play a central role in industrial automation. Its simplicity, openness, and reliability have allowed it to remain relevant despite massive changes in software and networking technologies.</p><p>For software developers, learning Modbus provides insight into how physical processes are monitored and controlled and how legacy systems integrate with modern software platforms.</p><p>Modbus may lack the conveniences of modern application protocols, but its continued use makes it an essential part of the industrial technology landscape.</p><p>I would like to thank <a href="https://medium.com/u/dba1bd4888ce">Ronak Jain</a> for sharing foundational notes and technical insights on the Modbus protocol, which helped shape the direction and understanding of this article.</p><p>If you’d like to connect, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5baa9bfc96aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finalizing YOLO Inference: Box Mapping and Visualization]]></title>
            <link>https://isvidhi.medium.com/finalizing-yolo-inference-box-mapping-and-visualization-249c67e5530d?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/249c67e5530d</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 03:28:59 GMT</pubDate>
            <atom:updated>2026-01-23T03:33:00.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uj91L_Wl-_ykOPY6RPTc6w.png" /></figure><p>In the previous post, we stopped after Non-Max Suppression, where overlapping predictions were filtered in letterboxed image space. While those detections are logically correct, they are still not ready to be displayed.</p><p>In this final part of the series, we complete the YOLO inference pipeline by mapping bounding boxes back to the original image and rendering the results. This step is purely geometric and visual, but getting it wrong leads to shifted or distorted boxes even when the model itself is working perfectly.</p><p>We will reverse the letterboxing transformation, explain why this must happen after NMS, and then draw clean, readable bounding boxes with class labels using OpenCV in C++. By the end, the detections produced by the model will align exactly with the original image pixels.</p><p>At this point in the pipeline, all the heavy lifting is already done.</p><pre>Original image<br>   ↓<br>Letterbox (scale + padding)<br>   ↓<br>YOLO inference<br>   ↓<br>Decode + NMS (letterboxed space)<br>   ↓<br>Map back to original image<br>   ↓<br>Draw boxes &amp; labels</pre><p>This blog completes the series by covering the <strong>final two steps</strong>:</p><ol><li>Mapping bounding boxes from letterboxed space back to the original image</li><li>Drawing boxes and labels for visual verification</li></ol><p>No new model logic is introduced here — this is about <strong>correct geometry and clean visualization</strong>.</p><h3>Where We Are After NMS</h3><p>After Non-Max Suppression, each detection contains a bounding box like this:</p><pre>cv::Rect box;</pre><p>Important detail:</p><blockquote><em>This box is still in </em><strong><em>letterboxed image space</em></strong><em> (e.g. 640×640)</em></blockquote><p>But the image you want to draw on is the <strong>original image</strong>:</p><pre>orig_w × orig_h</pre><p>So before drawing anything, we must <strong>reverse the letterboxing transform</strong>.</p><h3>What We Already Have from Preprocessing</h3><p>During letterboxing, we saved the following values:</p><pre>float scale;<br>int pad_x;<br>int pad_y;<br>int orig_w;<br>int orig_h;</pre><p>These values are <strong>mandatory</strong>.<br>Without them, mapping back correctly is impossible.</p><h3>The Core Idea: Inverse Letterboxing</h3><p>Letterboxing applies this transformation:</p><pre>original → scaled → padded</pre><p>To go back, we apply the inverse:</p><pre>padded → remove padding → unscale</pre><p>That’s the entire mental model.</p><h3>Step-by-Step Mapping Math</h3><p>Assume a bounding box in letterboxed space:</p><pre>(x1, y1, x2, y2)</pre><h3>1. Remove Padding</h3><pre>x1 -= pad_x;<br>x2 -= pad_x;<br>y1 -= pad_y;<br>y2 -= pad_y;</pre><h3>2. Reverse Scaling</h3><pre>x1 /= scale;<br>x2 /= scale;<br>y1 /= scale;<br>y2 /= scale;</pre><p>Now the box is in <strong>original image coordinates</strong>.</p><h3>3. Clamp to Image Boundaries</h3><p>Rounding errors can push boxes slightly outside the image.</p><pre>x1 = std::max(0.f, std::min(x1, (float)orig_w));<br>y1 = std::max(0.f, std::min(y1, (float)orig_h));<br>x2 = std::max(0.f, std::min(x2, (float)orig_w));<br>y2 = std::max(0.f, std::min(y2, (float)orig_h));</pre><h3>Clean C++ Implementation</h3><pre>void map_to_original(<br>    Detection&amp; det,<br>    float scale,<br>    int pad_x,<br>    int pad_y,<br>    int orig_w,<br>    int orig_h<br>) {<br>    float x1 = det.box.x;<br>    float y1 = det.box.y;<br>    float x2 = det.box.x + det.box.width;<br>    float y2 = det.box.y + det.box.height;<br><br>    // Remove padding<br>    x1 -= pad_x;<br>    x2 -= pad_x;<br>    y1 -= pad_y;<br>    y2 -= pad_y;<br><br>    // Reverse scale<br>    x1 /= scale;<br>    x2 /= scale;<br>    y1 /= scale;<br>    y2 /= scale;<br><br>    // Clamp<br>    x1 = std::max(0.f, std::min(x1, (float)orig_w));<br>    y1 = std::max(0.f, std::min(y1, (float)orig_h));<br>    x2 = std::max(0.f, std::min(x2, (float)orig_w));<br>    y2 = std::max(0.f, std::min(y2, (float)orig_h));<br>    det.box = cv::Rect(<br>        cv::Point((int)x1, (int)y1),<br>        cv::Point((int)x2, (int)y2)<br>    );<br>}</pre><p>Apply it to all detections <strong>after NMS</strong>:</p><pre>for (auto&amp; det : final_detections) {<br>    map_to_original(<br>        det,<br>        letterbox.scale,<br>        letterbox.pad_x,<br>        letterbox.pad_y,<br>        orig_w,<br>        orig_h<br>    );<br>}</pre><h3>Why Mapping Happens After NMS</h3><ul><li>NMS relies on IoU</li><li>IoU requires consistent geometry</li><li>Letterboxed space provides that consistency</li></ul><p>Mapping earlier breaks IoU and suppresses wrong boxes</p><p>Always remember:</p><blockquote><strong><em>NMS first, mapping later</em></strong></blockquote><h3>Common Mapping Mistakes</h3><ul><li>Forgetting to subtract padding</li><li>Dividing before removing padding</li><li>Using the wrong scale</li><li>Not clamping coordinates</li><li>Mapping before NMS</li></ul><p>All of these lead to shifted or distorted boxes.</p><h3>Final Stage: Drawing Boxes &amp; Labels</h3><p>Now we are truly at the end of the pipeline.</p><pre>Image<br>  ↓<br>YOLO inference<br>  ↓<br>Post-processing<br>  ↓<br>Final detections<br>  ↓<br>Draw boxes &amp; labels</pre><p>Each detection now looks like:</p><pre>struct Detection {<br>    cv::Rect box;       // original image space<br>    float confidence;<br>    int class_id;<br>};</pre><h3>Class Names</h3><p>Example (COCO):</p><pre>std::vector&lt;std::string&gt; class_names = {<br>    &quot;person&quot;, &quot;bicycle&quot;, &quot;car&quot;, &quot;motorbike&quot;, &quot;aeroplane&quot;,<br>    &quot;bus&quot;, &quot;train&quot;, &quot;truck&quot;, &quot;boat&quot;, &quot;traffic light&quot;<br>};</pre><p>The index <strong>must match model training</strong>.</p><h3>Stable Colors Per Class</h3><pre>cv::Scalar get_color(int class_id) {<br>    static std::vector&lt;cv::Scalar&gt; colors = {<br>        {255, 56, 56}, {255, 157, 151}, {255, 112, 31},<br>        {255, 178, 29}, {207, 210, 49}, {72, 249, 10},<br>        {146, 204, 23}, {61, 219, 134}, {26, 147, 52},<br>        {0, 212, 187}<br>    };<br>    return colors[class_id % colors.size()];<br>}</pre><h3>Drawing the Bounding Box</h3><pre>cv::rectangle(<br>    image,<br>    det.box,<br>    get_color(det.class_id),<br>    2<br>);</pre><h3>Label Format</h3><pre>class_name confidence</pre><p>Example:</p><pre>person 0.87</pre><pre>std::string label =<br>    class_names[det.class_id] + &quot; &quot; +<br>    cv::format(&quot;%.2f&quot;, det.confidence);</pre><h3>Label Background (Important for Readability)</h3><p>Measure text size:</p><pre>int baseline = 0;<br>cv::Size text_size = cv::getTextSize(<br>    label,<br>    cv::FONT_HERSHEY_SIMPLEX,<br>    0.5,<br>    1,<br>    &amp;baseline<br>);</pre><p>Draw background:</p><pre>cv::Rect bg(<br>    det.box.x,<br>    std::max(0, det.box.y - text_size.height - baseline),<br>    text_size.width,<br>    text_size.height + baseline<br>);<br><br>cv::rectangle(image, bg, get_color(det.class_id), cv::FILLED);</pre><p>Draw text:</p><pre>cv::putText(<br>    image,<br>    label,<br>    cv::Point(det.box.x, det.box.y - baseline),<br>    cv::FONT_HERSHEY_SIMPLEX,<br>    0.5,<br>    cv::Scalar(0, 0, 0),<br>    1<br>);</pre><h3>Full Drawing Loop</h3><pre>for (const auto&amp; det : final_detections) {<br>    cv::Scalar color = get_color(det.class_id);<br>cv::rectangle(image, det.box, color, 2);<br>    std::string label = class_names[det.class_id] + &quot; &quot; +<br>                        cv::format(&quot;%.2f&quot;, det.confidence);<br>    int baseline = 0;<br>    cv::Size text_size = cv::getTextSize(<br>        label,<br>        cv::FONT_HERSHEY_SIMPLEX,<br>        0.5,<br>        1,<br>        &amp;baseline<br>    );<br>    cv::Rect bg(<br>        det.box.x,<br>        std::max(0, det.box.y - text_size.height - baseline),<br>        text_size.width,<br>        text_size.height + baseline<br>    );<br>    cv::rectangle(image, bg, color, cv::FILLED);<br>    cv::putText(<br>        image,<br>        label,<br>        cv::Point(det.box.x, det.box.y - baseline),<br>        cv::FONT_HERSHEY_SIMPLEX,<br>        0.5,<br>        cv::Scalar(0, 0, 0),<br>        1<br>    );<br>}</pre><h3>Display or Save Output</h3><pre>cv::imshow(&quot;YOLO Detection&quot;, image);<br>cv::waitKey(0);<br>// or<br>cv::imwrite(&quot;result.jpg&quot;, image);</pre><h3>Final Mental Model</h3><blockquote><em>Drawing is not logic<br>Drawing is </em><strong><em>visual verification</em></strong></blockquote><p>If boxes look wrong, the bug is <strong>earlier in the pipeline</strong>, not here.</p><p>With this final step, the YOLO inference pipeline is complete. Starting from preprocessing and letterboxing, through ONNX Runtime inference, output decoding, confidence filtering, and Non-Max Suppression, we have now mapped detections back to the original image and rendered the results correctly.</p><p>At this stage, the model’s job is already done what remains is careful geometry and verification. If the boxes align with the image, the pipeline is correct; if they do not, the issue lies earlier, not in visualization.</p><p>This concludes the post-processing series and provides a full, end-to-end view of how YOLO inference works in a real C++ implementation.</p><p>If you’d like to connect, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=249c67e5530d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Non-Max Suppression Explained: How YOLO Eliminates Duplicate Detections]]></title>
            <link>https://isvidhi.medium.com/non-max-suppression-explained-how-yolo-eliminates-duplicate-detections-d046a46c8646?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/d046a46c8646</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 11:12:54 GMT</pubDate>
            <atom:updated>2026-01-17T11:12:54.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdDNDrCAO361XispMMi-EQ.png" /></figure><p>Modern object detectors like YOLO don’t fail because they miss objects they fail because they predict <strong>too many boxes</strong>.</p><p>A single person in an image might be detected five or six times, each box slightly shifted, all with high confidence. Left untreated, this results in noisy outputs that are unusable in real applications.</p><p>This is where <strong>Non-Max Suppression (NMS)</strong> comes in.</p><p>NMS is the final filtering step in the detection pipeline. It doesn’t find objects — it <strong>decides which predictions actually matter</strong>. Using a simple geometric idea called <em>Intersection over Union (IoU)</em>, NMS removes redundant boxes and keeps only the strongest detections.</p><p>By the end, you’ll understand not just <em>what</em> NMS does, but <em>why it works</em> and <em>how to implement it correctly</em>.</p><h3>Where NMS fits</h3><p>At this point, the detection pipeline looks like this:</p><pre>Image<br>  ↓<br>Preprocessing<br>  ↓<br>session.Run()<br>  ↓<br>Decode + Confidence Thresholding<br>  ↓<br>Non-Max Suppression   ← WE ARE HERE<br>  ↓<br>Final boxes</pre><p>Everything before NMS is about <em>finding</em> candidate boxes. NMS is about <em>deciding which ones actually survive</em>.</p><h3>Why NMS is required</h3><p>YOLO predicts <strong>multiple boxes for the same object</strong>.</p><p>Typical situation:</p><ul><li>One person detected 5–6 times</li><li>Boxes are slightly shifted</li><li>All have high confidence</li></ul><p>Without NMS, you would draw <strong>multiple boxes on the same object</strong>.</p><p>What we really want is simple:</p><blockquote><strong><em>One object → one box</em></strong></blockquote><h3>What NMS does (plain English)</h3><p>For each object</p><ul><li>Keep the <strong>best box</strong></li><li>Remove overlapping weaker boxes</li></ul><p>That’s it. Everything else is just how we define <em>best</em> and <em>overlapping</em>.</p><h3>Key concept: IoU (Intersection over Union)</h3><p>NMS relies entirely on <strong>IoU</strong> to decide whether two boxes represent the same object.</p><h3>Definition</h3><pre>IoU = Area of Overlap / Area of Union</pre><p>Range:</p><ul><li>0.0 → no overlap</li><li>1.0 → identical boxes</li></ul><h3>IoU computation (math)</h3><p>For two boxes <strong>A</strong> and <strong>B</strong>:</p><pre>inter_x1 = max(A.x1, B.x1)<br>inter_y1 = max(A.y1, B.y1)<br>inter_x2 = min(A.x2, B.x2)<br>inter_y2 = min(A.y2, B.y2)</pre><p>If:</p><pre>inter_x2 &lt;= inter_x1 or inter_y2 &lt;= inter_y1</pre><p>→ <strong>IoU = 0</strong></p><p>Otherwise:</p><pre>inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)<br>union_area = area(A) + area(B) - inter_area<br>IoU = inter_area / union_area</pre><h3>What IoU answers</h3><blockquote><em>“How much do two boxes overlap?”</em></blockquote><ul><li>IoU = 0 → no overlap</li><li>IoU = 1 → perfect overlap</li></ul><p>NMS is simply a repeated application of this question.</p><h3>Step 0: Box representation (important)</h3><p>Each box is represented as:</p><pre>(x1, y1) = top-left<br>(x2, y2) = bottom-right</pre><p>Visualized:</p><pre>A:<br>(x1_A, y1_A) --------<br>      |              |<br>      |              |<br>      -------- (x2_A, y2_A)</pre><p>This corner-based representation is essential for correct IoU computation.</p><h3>Step 1: Find intersection rectangle</h3><p>The overlap itself is also a rectangle.</p><pre>inter_x1 = max(A.x1, B.x1);<br>inter_y1 = max(A.y1, B.y1);<br>inter_x2 = min(A.x2, B.x2);<br>inter_y2 = min(A.y2, B.y2);</pre><h3>Why max for top-left?</h3><p>You want the <strong>inner</strong> left/top edge.</p><h3>Why min for bottom-right?</h3><p>You want the <strong>inner</strong> right/bottom edge.</p><p>This gives the overlapping region <strong>if it exists</strong>.</p><h3>Step 2: Check if overlap exists</h3><pre>if (inter_x2 &lt;= inter_x1 || inter_y2 &lt;= inter_y1)<br>    IoU = 0;</pre><h3>Why this works</h3><p>If:</p><ul><li>width ≤ 0 OR</li><li>height ≤ 0</li></ul><p>then the boxes do not overlap.</p><p>Touching edges ≠ overlap → <strong>IoU = 0</strong>.</p><h3>Step 3: Compute intersection area</h3><p>If overlap exists:</p><pre>inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1);</pre><p>This is simply:</p><pre>width × height</pre><h3>Step 4: Compute union area</h3><p>Union means:</p><blockquote><em>Total area covered by both boxes</em></blockquote><pre>union_area = area(A) + area(B) - inter_area;</pre><p>Why subtract inter_area?</p><p>Because it was counted <strong>twice</strong>.</p><h3>Step 5: Final IoU</h3><pre>IoU = inter_area / union_area;</pre><p>This is the overlap <strong>ratio</strong>, always between 0 and 1.</p><h3>Visual intuition</h3><pre>IoU = overlap area / total covered area</pre><ul><li>Big overlap → large IoU</li><li>Small overlap → small IoU</li></ul><h3>Why IoU is used in NMS</h3><p>During NMS, we ask:</p><blockquote><em>“Are these two boxes basically the same detection?</em></blockquote><p>If:</p><pre>IoU &gt; threshold (e.g. 0.5)</pre><p>then:</p><ul><li>Keep the higher-confidence box</li><li>Suppress the other</li></ul><h3>Typical IoU thresholds</h3><p>UseIoUYOLO NMS0.4–0.6Strict overlap≥ 0.7Loose overlap≤ 0.3</p><h3>Common mistakes</h3><p>Forgetting - inter_area in union</p><p>Using center-width-height instead of corners</p><p>Allowing negative intersection area</p><h3>One-line mental model 🧠</h3><blockquote><em>IoU = “How much do these two boxes sit on top of each other?”</em></blockquote><h3>Where this fits in the pipeline</h3><pre>Decoded boxes<br>   ↓<br>Confidence threshold<br>   ↓<br>IoU computation<br>   ↓<br>NMS (suppress overlaps)<br>   ↓<br>Final detections</pre><p>At this point, quantity has already been reduced. Now we remove redundancy.</p><h3>NMS threshold</h3><p>Typical values:</p><ul><li>0.45 (YOLO default)</li><li>0.5 (more strict)</li><li>0.3 (aggressive suppression)</li></ul><p>We’ll use:</p><pre>float nms_thresh = 0.45f;</pre><h3>NMS algorithm (step-by-step)</h3><p>1️. Sort boxes by confidence (descending)</p><p>2️. Pick highest-confidence box</p><p>3️. Remove all boxes with IoU &gt; threshold</p><p>4️. Repeat until no boxes left</p><p>Before jumping into code, keep one thing in mind: <strong>this algorithm only works if detections are sorted by confidence</strong>.</p><h3>C++ implementation (clean &amp; readable)</h3><h3>Step 1: IoU function</h3><pre>float IoU(const cv::Rect&amp; a, const cv::Rect&amp; b) {<br>    int x1 = std::max(a.x, b.x);<br>    int y1 = std::max(a.y, b.y);<br>    int x2 = std::min(a.x + a.width,  b.x + b.width);<br>    int y2 = std::min(a.y + a.height, b.y + b.height);<br>    int inter_area = std::max(0, x2 - x1) * std::max(0, y2 - y1);<br>    int union_area = a.area() + b.area() - inter_area;<br>    return union_area &gt; 0 ? (float)inter_area / union_area : 0.0f;<br>}</pre><h3>Step 2: Sort by confidence</h3><pre>std::sort(detections.begin(), detections.end(),<br>    [](const Detection&amp; a, const Detection&amp; b) {<br>        return a.confidence &gt; b.confidence;<br>    });</pre><p>This ordering is <strong>non-negotiable</strong> for greedy NMS.</p><h3>Step 3: NMS loop</h3><pre>std::vector&lt;Detection&gt; final_detections;<br><br>std::vector&lt;bool&gt; suppressed(detections.size(), false);<br>for (size_t i = 0; i &lt; detections.size(); i++) {<br>    if (suppressed[i]) continue;<br>    final_detections.push_back(detections[i]);<br>    for (size_t j = i + 1; j &lt; detections.size(); j++) {<br>        if (suppressed[j]) continue;<br>        float iou = IoU(detections[i].box, detections[j].box);<br>        if (iou &gt; nms_thresh) {<br>            suppressed[j] = true;<br>        }<br>    }<br>}</pre><p>Now:</p><ul><li>Duplicate boxes are removed</li><li>Only the strongest boxes remain</li></ul><p>This code implements <strong>Greedy Non‑Maximum Suppression (NMS)</strong>.</p><p>Goal:</p><blockquote><em>From many overlapping boxes, keep the best one and suppress the rest.</em></blockquote><p><strong>Key assumption:</strong></p><p>👉 detections is <strong>already sorted by confidence score (descending)</strong>.</p><p>If not, this implementation is <strong>incorrect</strong>.</p><h3>Step 1: Data structures</h3><pre>std::vector&lt;Detection&gt; final_detections;</pre><p>Holds the <strong>boxes we decide to keep</strong>.</p><pre>std::vector&lt;bool&gt; suppressed(detections.size(), false);</pre><ul><li>One flag per detection</li><li>false → still alive</li><li>true → suppressed</li></ul><p>💡 Why a separate array?</p><ul><li>Avoid erasing elements while iterating</li><li>O(1) marking</li></ul><h3>Step 2: Outer loop (choose a “winner” box)</h3><pre>for (size_t i = 0; i &lt; detections.size(); i++) {</pre><p>We iterate <strong>in confidence order</strong>.</p><p>Earlier boxes have higher priority.</p><pre>if (suppressed[i]) continue;</pre><p>If this box was already killed by a stronger one, skip it.</p><pre>final_detections.push_back(detections[i]);</pre><p>Once a box survives suppression, it is <strong>final</strong>.</p><p>This box becomes the reference that suppresses weaker overlaps.</p><h3>Step 3: Inner loop (suppress weaker boxes)</h3><pre>for (size_t j = i + 1; j &lt; detections.size(); j++) {</pre><p>Why start from i + 1?</p><ul><li>j &lt; i → higher-confidence boxes (already processed)</li><li>j &gt; i → lower-confidence boxes (eligible for suppression)</li></ul><p>High confidence always suppresses low confidence — never the reverse.</p><pre>if (suppressed[j]) continue;</pre><p>Already-dead boxes are ignored.</p><pre>float iou = IoU(detections[i].box, detections[j].box);</pre><p>Compute overlap between:</p><ul><li>Current winner (i)</li><li>Candidate weaker box (j)</li></ul><pre>if (iou &gt; nms_thresh) {<br>    suppressed[j] = true;<br>}</pre><p>If overlap is too high:</p><ul><li>Boxes represent the same object</li><li>Keep the stronger one</li><li>Suppress the weaker one</li></ul><h3>Visual intuition</h3><pre>[Box A 0.92]  ← kept<br>[Box B 0.85]  ← suppressed (IoU &gt; thresh with A)<br>[Box C 0.80]  ← suppressed (IoU &gt; thresh with A)<br>[Box D 0.60]  ← kept (IoU small with A)</pre><p>Flow:</p><ul><li>Pick A → suppress B &amp; C</li><li>Skip B, skip C</li><li>Pick D → done</li></ul><h3>Time complexity</h3><ul><li>Worst case: <strong>O(N²)</strong></li><li>Typical after thresholding: manageable</li></ul><p>YOLO normally:</p><ul><li>Threshold → N ≈ few hundred</li><li>NMS → fast enough on CPU</li></ul><h3>Hidden assumptions (very important)</h3><h3>1. Detections must be sorted</h3><p>Before NMS:</p><pre>std::sort(detections.begin(), detections.end(),<br>    [](const Detection&amp; a, const Detection&amp; b) {<br>        return a.confidence &gt; b.confidence;<br>    });</pre><p>Otherwise, weaker boxes may suppress stronger ones.</p><h3>2. This is class‑agnostic NMS</h3><p>This code suppresses boxes <strong>across all classes</strong>.</p><p>Meaning:</p><ul><li>A “person” box can suppress a “dog” box</li></ul><p>YOLO typically uses <strong>class‑wise NMS</strong>.</p><h3>How class‑wise NMS differs</h3><p>Instead of one list:</p><pre>std::unordered_map&lt;int, std::vector&lt;Detection&gt;&gt; by_class;</pre><p>Run NMS <strong>inside each class group</strong>.</p><h3>Why NMS must run in letterboxed space</h3><p>Because:</p><ul><li>All boxes share the same coordinate system</li><li>IoU must be computed <strong>before mapping back</strong></li></ul><p>Mapping earlier breaks geometry.</p><h3>Common NMS mistakes</h3><p>Running NMS before confidence filtering</p><p>Using global NMS across classes</p><p>Mapping boxes before NMS</p><p>Incorrect IoU calculation</p><blockquote><em>Confidence thresholding reduces quantity<br>NMS reduces redundancy</em></blockquote><p>Together, they produce <strong>clean detections</strong>.</p><p>In the next step of the pipeline, these final boxes are mapped back to the original image space for visualization.</p><p>At this stage of the pipeline, we’re left with a small set of strong boxes, all defined in the letterboxed coordinate space. The final step is to <strong>map these boxes back to the original image</strong>, restoring their true position and scale for visualization or downstream use.</p><p>With NMS done correctly, the model’s output finally becomes something you can put on the screen and rely on.</p><p>If you’d like to connect, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d046a46c8646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Most Misunderstood Part of YOLO: Confidence Thresholding & Box Decoding]]></title>
            <link>https://isvidhi.medium.com/the-most-misunderstood-part-of-yolo-confidence-thresholding-box-decoding-076d57222e59?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/076d57222e59</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 12:56:38 GMT</pubDate>
            <atom:updated>2026-01-14T12:56:38.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9MMnWYGS9HWE5BxblC0dg.png" /></figure><p>When people talk about YOLO, most of the focus is on the model architecture or training strategy. But in real-world systems, <strong>what happens after inference matters just as much</strong>.</p><p>Once session.Run() returns, YOLO doesn’t give you clean detections it gives you a dense tensor filled with thousands of raw predictions. Turning that tensor into accurate bounding boxes requires a precise post-processing pipeline. A small mistake here can completely break detection quality, even if the model itself is correct.</p><p>In this post, we’ll focus on two critical steps in YOLO post-processing <strong>confidence thresholding</strong> and <strong>box decoding</strong> from a C++ implementation perspective. These steps decide which predictions are worth keeping and how raw model outputs are transformed into real bounding boxes, setting the foundation for correct Non-Maximum Suppression (NMS).</p><p>At this point in the YOLO inference pipeline, the model has already done its job.</p><pre>session.Run()<br>   ↓<br>YOLO output tensor<br>   ↓<br>Confidence thresholding<br>   ↓<br>Box decoding<br>   ↓<br>NMS</pre><p>What remains is <strong>turning raw numbers into meaningful detections</strong>.<br>This post breaks down the two most misunderstood steps in that process: <strong>confidence thresholding</strong> and <strong>box decoding</strong>, with a C++ perspective.</p><h3>Why confidence thresholding exists</h3><p>A YOLO model does not output “final detections”.</p><p>Instead, it predicts <strong>thousands of candidate boxes</strong> (for example, ~8400 in YOLOv5/YOLOv8).<br>Most of these boxes represent:</p><ul><li>Background region</li><li>Extremely low confidence predictions</li><li>Pure noise</li></ul><p>Passing all of them to Non-Maximum Suppression (NMS) would be wasteful and harmful.</p><p>Confidence thresholding exists to:</p><ul><li>Reduce computational cost before NMS</li><li>Improve detection quality</li><li>Eliminate obvious garbage predictions early</li></ul><p>In short, <strong>not every predicted box deserves further consideration</strong>.</p><h3>What “confidence” actually means in YOLO</h3><p>In classic YOLO-style models, confidence is not a single value.</p><p>It is computed as:</p><pre>confidence = objectness × class_probability</pre><p>Where:</p><ul><li><strong>Objectness</strong> answers: <em>“Is there any object here at all?”</em></li><li><strong>Class probability</strong> answers: <em>“What object is it?”</em></li></ul><p>Only when <strong>both</strong> are high does a box represent a meaningful detection.</p><h3>Choosing a confidence threshold</h3><p>Common values you’ll see in practice:</p><ul><li>0.25 → YOLO default (balanced)</li><li>0.4 → stricter filtering</li><li>0.1 → recall-heavy or debugging</li></ul><p>For this implementation, we’ll use:</p><pre>float conf_thresh = 0.25f;</pre><p>This value removes most low-quality predictions while preserving valid detections.</p><h3>Raw box format (quick recap)</h3><p>Each YOLO prediction gives bounding boxes in <strong>center-based format</strong>:</p><pre>x, y, w, h</pre><p>Where:</p><ul><li>(x, y) → box center</li><li>(w, h) → width and height</li></ul><p>⚠️ Important:<br>These values are expressed in <strong>letterboxed image space</strong>, not the original image.</p><h3>Why box decoding is required</h3><p>YOLO outputs boxes in center format because it’s convenient for training.</p><p>However, most post-processing steps — including IoU computation and visualization — expect <strong>corner-based boxes</strong>:</p><pre>(x1, y1, x2, y2)</pre><p>So we must convert:</p><pre>(x, y, w, h)<br>   ↓<br>(x1, y1, x2, y2)</pre><h3>Center → corner conversion</h3><p>The conversion is straightforward:</p><pre>float x1 = x - w / 2;<br>float y1 = y - h / 2;<br>float x2 = x + w / 2;<br>float y2 = y + h / 2;</pre><p>At this stage, the box is still in <strong>letterboxed coordinates</strong> and that’s intentional.</p><h3>Full confidence thresholding + decoding loop (C++)</h3><p>Below is a minimal but complete decoding loop:</p><pre>struct Detection {<br>    cv::Rect box;<br>    float confidence;<br>    int class_id;<br>};<br><br>std::vector&lt;Detection&gt; detections;<br>int num_boxes = shape[1];<br>int elements = shape[2];<br>for (int i = 0; i &lt; num_boxes; i++) {<br>    float obj = data[i * elements + 4];<br>    if (obj &lt; 1e-6) continue;<br>    // Find best class<br>    float max_class = 0.0f;<br>    int class_id = -1;<br>    for (int c = 5; c &lt; elements; c++) {<br>        float score = data[i * elements + c];<br>        if (score &gt; max_class) {<br>            max_class = score;<br>            class_id = c - 5;<br>        }<br>    }<br>    float confidence = obj * max_class;<br>    if (confidence &lt; conf_thresh) continue;<br>    // Decode box<br>    float x = data[i * elements + 0];<br>    float y = data[i * elements + 1];<br>    float w = data[i * elements + 2];<br>    float h = data[i * elements + 3];<br>    float x1 = x - w / 2;<br>    float y1 = y - h / 2;<br>    float x2 = x + w / 2;<br>    float y2 = y + h / 2;<br>    cv::Rect box(<br>        cv::Point(x1, y1),<br>        cv::Point(x2, y2)<br>    );<br>    detections.push_back({box, confidence, class_id});<br>}</pre><p>At this point:</p><ul><li>Low-confidence predictions are removed</li><li>Boxes are decoded into usable geometry</li><li>Duplicate detections still exist</li></ul><p>That last part is exactly why NMS comes next.</p><h3>Why scale &amp; padding are NOT removed yet</h3><p>A common mistake is mapping boxes back to the original image <strong>before</strong> NMS.</p><p>This is wrong. At this stage:</p><ul><li>Boxes are in <strong>letterboxed image space</strong></li><li>All boxes share the same coordinate system</li></ul><p>NMS relies on <strong>IoU comparisons</strong>, which only work correctly when boxes are in the same space.</p><p>So the correct order is:</p><pre>Decode → NMS → map back to original image</pre><p>Mapping earlier will break IoU and cause incorrect suppression.</p><h3>Common decoding mistakes</h3><p>These errors appear frequently in YOLO implementations:</p><ul><li>Using class score alone as confidence</li><li>Running NMS before confidence thresholding</li><li>Mapping boxes back before NMS</li><li>Forgetting center-to-corner conversion</li></ul><p>The result is usually:</p><ul><li>Too many boxes</li><li>Poor suppression</li><li>Misaligned detections</li></ul><h3>The mental model to remember</h3><p>Confidence thresholding answers:</p><blockquote><strong><em>“Is this box worth considering at all?”</em></strong></blockquote><p>Box decoding answers:</p><blockquote><strong><em>“Where exactly is this box located?”</em></strong></blockquote><p>Once these two questions are answered correctly, NMS becomes both efficient and reliable.</p><p>At this stage in the pipeline, YOLO’s raw output has finally been shaped into something meaningful. Low-confidence noise has been filtered out, bounding boxes have been decoded into usable geometry, and the data is now ready for proper suppression.</p><p>Confidence thresholding and box decoding may look like simple arithmetic, but they quietly determine the quality of everything that follows. Get them right, and NMS behaves exactly as intended. Get them wrong, and even a perfectly trained model will produce unstable or misaligned detections.</p><p>With these foundations in place, the next step is straightforward: <strong>Non-Maximum Suppression</strong>, where overlapping predictions are reduced to the final set of detections that actually matter</p><p>If you’d like to connect, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=076d57222e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside YOLO Inference: How Raw Predictions Become Bounding Boxes]]></title>
            <link>https://isvidhi.medium.com/inside-yolo-inference-how-raw-predictions-become-bounding-boxes-acc39db0a676?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/acc39db0a676</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 12:28:28 GMT</pubDate>
            <atom:updated>2026-01-11T12:28:28.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*TrYwDdfKhErPBCoIr4n00g.png" /></figure><p>If you’ve ever run a YOLO model through <strong>ONNX Runtime</strong> and printed the output tensor, you’ve probably had this reaction:</p><blockquote>“Why am I getting thousands of numbers instead of bounding boxes?”</blockquote><p>This confusion usually comes from a common misconception <strong>YOLO does not output final detections</strong>.<br>What it actually produces is a <strong>large tensor of raw predictions</strong>, containing thousands of <em>candidate boxes</em>, each with geometry, objectness confidence, and class probabilities. At this stage, YOLO is essentially saying:</p><blockquote>“Here are many possible boxes. You decide which ones are real.”</blockquote><p>Understanding this output tensor is the <strong>single most important step</strong> in correctly deploying YOLO models in production especially when working with <strong>C++ and ONNX Runtime</strong>, where nothing is abstracted away for you.</p><p>If you’ve ever struggled with YOLO post-processing, incorrect indexing, or confidence calculations that “almost work but not quite”, this post is meant to remove that confusion for good.</p><p>Let’s start by understanding what YOLO <em>actually</em> outputs and why bounding boxes don’t exist yet.</p><p>Before we look at tensor shapes or indexing, it’s important to understand <strong>where exactly we are in the YOLO inference flow</strong>.</p><p>A typical YOLO inference pipeline looks like this:</p><pre>Image<br>  ↓<br>Preprocessing (resize, letterbox, normalize)<br>  ↓<br>ONNX Runtime inference<br>  ↓<br>session.Run()<br>  ↓<br>Ort::Value (YOLO output tensor)   ← WE ARE HERE<br>  ↓<br>Post-processing (decode + filter + NMS)<br>  ↓<br>Final bounding boxes</pre><p>At this point:</p><ul><li>The model has already run successfully</li><li>ONNX Runtime has returned an Ort::Value</li><li>No bounding boxes exist yet</li></ul><p>What we have is a <strong>raw output tensor</strong>, and our job is to <strong>interpret and decode it correctly</strong>.</p><h4>What session.Run() Actually Returns</h4><p>After calling ONNX Runtime inference:</p><pre>std::vector&lt;Ort::Value&gt; output_tensors = session.Run(<br>    Ort::RunOptions{nullptr},<br>    input_names.data(),<br>    &amp;input_tensor,<br>    1,<br>    output_names.data(),<br>    output_names.size()<br>);</pre><p>You receive one or more Ort::Value objects.</p><p>For YOLO models, the first output is typically:</p><ul><li>A <strong>3D tensor</strong></li><li>Containing predictions for <strong>thousands of candidate boxes</strong></li><li>With <strong>no filtering or decoding applied</strong></li></ul><p>This tensor is <strong>not human-readable</strong>, and it is <strong>not final output</strong>.</p><h4>First: what YOLO actually outputs</h4><p>YOLO does NOT output final boxes. It outputs <strong>raw predictions</strong> for <strong>many candidate boxes</strong>.</p><h4>Think of YOLO as a “proposal generator”</h4><p>YOLO effectively says:</p><blockquote><em>“Here are thousands of possible boxes.<br> You decide which ones are real.”</em></blockquote><h4>What is a “candidate box”?</h4><p>Each candidate corresponds to:</p><ul><li>A grid cell</li><li>An anchor (depending on the YOLO version)</li></ul><p>YOLO predicts <strong>many</strong> such candidates per image.</p><h4>What each candidate contains</h4><p>For <strong>each candidate</strong>, YOLO outputs a vector with three parts.</p><h4>1. Box geometry</h4><p>Usually 4 values:</p><pre>tx, ty, tw, th</pre><p>These are <strong>not final pixel coordinates</strong>.</p><p>They represent:</p><ul><li>Offsets relative to a grid cell</li><li>Width and height in model space</li></ul><h4>2. Objectness confidence</h4><p>One value:</p><pre>objectness</pre><p>This answers:</p><blockquote><em>“Is there any object here?”</em></blockquote><p>Value range:</p><pre>0 → background<br>1 → object</pre><h4>3. Class scores</h4><p>One value per class:</p><pre>c1, c2, c3, ..., cN</pre><p>These answer:</p><blockquote><em>“If there is an object, what is it?”</em></blockquote><p>These are <strong>conditional probabilities</strong>.<br>One candidate vector (example)</p><p>For COCO (80 classes):</p><pre>[ tx, ty, tw, th, objectness, c1, c2, ..., c80 ]</pre><p>Total values per candidate:</p><pre>4 + 1 + 80 = 85</pre><h4>How many candidates are there?</h4><p>For example, YOLOv5 at 640×640 uses:</p><ul><li>Multiple detection heads</li><li>Multiple grid sizes</li><li>Multiple anchors</li></ul><p>Total candidates ≈ <strong>25,000+</strong>.<br>Now that we understand <strong>what YOLO predicts</strong>, the next step is to see <strong>how these predictions are laid out in memory</strong>.</p><h4>Typical YOLOv5 / YOLOv8 ONNX Output Shape</h4><p>Once inference completes, ONNX Runtime returns the YOLO output as a <strong>3D tensor</strong>.</p><p>The most common shape looks like this:</p><pre>[1, N, C]</pre><p>Where:</p><p>1means batch size, N- number of predicted boxes,C- values per box.</p><h4>Example: YOLOv8 trained on COCO</h4><p>A typical output shape is:</p><pre>[1, 8400, 85]</pre><p>This means:</p><ul><li>One image was processed</li><li>The model predicted <strong>8400 candidate boxes</strong></li><li>Each candidate box is represented by <strong>85 values</strong></li></ul><h4>What determines C?</h4><p>The value of C is fixed by the model configuration:</p><pre>C = 4 + 1 + num_classes</pre><p>For COCO (80 classes):</p><pre>C = 4 + 1 + 80 = 85</pre><p>So for every candidate box, YOLO outputs:</p><ul><li>4 values for box geometry</li><li>1 value for objectness</li><li>80 values for class scores</li></ul><h4>Important clarification</h4><p>This tensor does <strong>not</strong> represent final detections.</p><p>Each of the N rows corresponds to a <strong>candidate box</strong>, not a confirmed object.</p><p>At this stage:</p><ul><li>All candidates are present</li><li>No filtering has happened</li><li>No decoding has happened</li></ul><p>Knowing the tensor shape is not enough we also need to understand <strong>what each value inside </strong><strong>C actually represents</strong>.</p><p>Great, continuing with the same constraints.<br>Here is the <strong>next section</strong>, refined and transitioned, with your content kept intact.</p><h4>What Is Inside C (VERY IMPORTANT)</h4><p>The last dimension of the YOLO output tensor contains all the information for <strong>one candidate box</strong>.</p><p>Its size is defined as:</p><pre>C = 4 + 1 + num_classes</pre><h4>Per-box layout</h4><p>Each row in the [N, C] tensor follows this layout:</p><pre>[x, y, w, h, obj, cls0, cls1, ..., clsN]</pre><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*rZNwZsTPqk0iQ6qict6iCw.png" /></figure><h4>Important notes</h4><ul><li>(x, y, w, h) are <strong>not corner coordinates</strong></li><li>They are expressed in <strong>model input space</strong></li><li>Depending on the export, values may be normalized or already scaled</li></ul><p>These values still require decoding before they can be drawn on the image.</p><p>At this point, you must still:</p><ol><li>Convert (x, y, w, h) → (x1, y1, x2, y2)</li><li>Combine objectness with class probability</li><li>Filter low-confidence predictions</li><li>Apply Non-Maximum Suppression (NMS)</li></ol><p>Now that we understand <strong>what each candidate box contains</strong>, the next step is to see <strong>how to access this tensor in C++ using ONNX Runtime</strong>.</p><h4>Accessing the Output Tensor in C++</h4><p>After running inference with ONNX Runtime, the YOLO output is available as an Ort::Value.</p><p>A typical inference call looks like this:</p><pre>std::vector&lt;Ort::Value&gt; output_tensors = session.Run(<br>    Ort::RunOptions{nullptr},<br>    input_names.data(),<br>    &amp;input_tensor,<br>    1,<br>    output_names.data(),<br>    output_names.size()<br>);</pre><p>For most YOLO models, the first output tensor contains all predictions.</p><h3>Getting the tensor shape</h3><p>To interpret the output, the first step is to inspect its shape:</p><pre>auto&amp; output = output_tensors[0];</pre><pre>auto type_info = output.GetTensorTypeAndShapeInfo();<br>std::vector&lt;int64_t&gt; shape = type_info.GetShape();</pre><p>Example result:</p><pre>shape = {1, 8400, 85}</pre><p>This directly matches the [1, N, C] layout discussed earlier.</p><h4>Accessing the raw data pointer</h4><p>Once the shape is known, you can access the underlying data:</p><pre>float* data = output.GetTensorMutableData&lt;float&gt;();</pre><p>At this point:</p><ul><li>data is a <strong>flat 1D array</strong></li><li>All tensor values are stored contiguously in memory</li><li>The original 3D shape is no longer explicit</li></ul><p>Understanding how to index into this array is critical.</p><h4>How Indexing Works (THIS IS KEY)</h4><p>At this stage, ONNX Runtime has given us:</p><pre>float* data;</pre><p>This is a <strong>flat 1D array</strong>, even though the original tensor shape was:</p><pre>[1, num_boxes, elements_per_box]</pre><p>Understanding how this flattened memory maps back to the tensor is critical.</p><h4>What the YOLO output really is in memory</h4><p>Conceptually, the output tensor looks like:</p><pre>[batch][boxes][elements]</pre><p>With batch size = 1:</p><pre>[1][num_boxes][elements_per_box]</pre><p>In memory, ONNX Runtime stores this tensor in <strong>row-major order</strong>.</p><h4>What “row-major” means here</h4><p>Row-major means:</p><blockquote><em>The </em><strong><em>last dimension changes fastest</em></strong><em>.</em></blockquote><p>So the memory layout is:</p><pre>Box 0: [x y w h obj cls0 cls1 ...]<br>Box 1: [x y w h obj cls0 cls1 ...]<br>Box 2: [x y w h obj cls0 cls1 ...]<br>...</pre><p>All values for <strong>one box</strong> are stored contiguously, followed by the next box.</p><h4>Flattened memory view (example)</h4><p>Imagine a small tensor:</p><pre>[1][3][5]   // batch = 1, boxes = 3, elements = 5</pre><p>Flattened in memory, it looks like:</p><pre>Index:  0   1   2   3   4 | 5   6   7   8   9 | 10  11  12  13  14<br>Data : [b0e0 b0e1 b0e2 b0e3 b0e4 | b1e0 b1e1 b1e2 b1e3 b1e4 | b2e0 ...]</pre><p>Each box occupies a <strong>fixed-size block</strong> in memory.</p><h4>Why this indexing formula works</h4><p>To access:</p><ul><li>box i</li><li>element j inside that box</li></ul><p>You use:</p><pre>index = i * elements_per_box + j</pre><p>Because:</p><ul><li>Each box uses elements_per_box values</li><li>To reach box i, you skip i full blocks</li><li>Then offset by j within that block</li></ul><h4>Applying this to the YOLO output</h4><p>From the tensor shape:</p><pre>int num_boxes = shape[1];<br>int elements_per_box = shape[2];</pre><p>This means:</p><ul><li>shape[1] → number of candidate boxes</li><li>shape[2] → values per box</li></ul><h4>Extracting box values</h4><p>Using the indexing rule:</p><pre>for (int i = 0; i &lt; num_boxes; i++) {<br>    float x   = data[i * elements_per_box + 0];<br>    float y   = data[i * elements_per_box + 1];<br>    float w   = data[i * elements_per_box + 2];<br>    float h   = data[i * elements_per_box + 3];<br>    float obj = data[i * elements_per_box + 4];<br>}</pre><p>Each iteration processes <strong>one candidate box</strong>.</p><h4>Why batch is ignored</h4><p>The batch dimension exists, but here:</p><pre>batch = 1</pre><p>So its offset is zero.</p><p>If batch size were greater than 1, indexing would become:</p><pre>index = b * (num_boxes * elements_per_box)<br>      + i * elements_per_box<br>      + j</pre><p>But for YOLO inference, batch size is typically 1.</p><p>We can use the same logic to extract <strong>class scores</strong> and determine <strong>which class each box predicts</strong>.</p><h4>Class Score Extraction</h4><p>So far, we’ve extracted:</p><ul><li>Box geometry</li><li>Objectness score</li></ul><p>The remaining values in each candidate box correspond to <strong>class probabilities</strong>.</p><h4>Where class scores start</h4><p>From the per-box layout:</p><pre>[x, y, w, h, obj, cls0, cls1, ..., clsN]</pre><p>Class scores begin at index:</p><pre>int class_start = 5;</pre><h4>Determining the number of classes</h4><p>Rather than hardcoding the number of classes, we compute it from the tensor shape:</p><pre>int num_classes = elements_per_box - class_start;</pre><p>For example, if:</p><pre>elements_per_box = 85</pre><p>Then:</p><pre>num_classes = 80</pre><p>This makes the code model-agnostic.</p><h4>Finding the best class for a candidate</h4><p>For each candidate box, we scan all class scores and select the highest one:</p><pre>float max_class_score = 0.0f;<br>int class_id = -1;</pre><pre>for (int c = 0; c &lt; num_classes; c++) {<br>    float score = data[i * elements_per_box + class_start + c];<br>    if (score &gt; max_class_score) {<br>        max_class_score = score;<br>        class_id = c;<br>    }<br>}</pre><p>At the end of this loop:</p><ul><li>class_id is the predicted class</li><li>max_class_score is the highest class probability</li></ul><h4>Important clarification</h4><p>This is <strong>not</strong> the final confidence score.</p><p>At this stage:</p><ul><li>We have the best class prediction</li><li>But objectness has not been applied yet</li></ul><p>Next, we’ll combine <strong>objectness</strong> and <strong>class probability</strong> to compute the <strong>final confidence score</strong> used for filtering detections.</p><h4>Final Confidence Score</h4><p>Once we have:</p><ul><li>Objectness score</li><li>Highest class probability</li></ul><p>We combine them to compute the <strong>final confidence</strong> for a candidate box.</p><pre>float confidence = obj * max_class_score;</pre><h4>Why this formula is correct</h4><p>YOLO predicts two probabilities:</p><ul><li><strong>Objectness</strong></li><li>P(object exists)</li><li><strong>Class score</strong></li><li>P(class | object exists)</li></ul><p>From probability theory:</p><pre>P(class AND object) = P(object) × P(class | object)</pre><p>This is exactly what the confidence score represents.</p><p>Both signals must be high.</p><p>Examples:</p><pre>obj = 0.9, class = 0.9 → confidence = 0.81<br>obj = 0.1, class = 0.9 → confidence = 0.09<br>obj = 0.9, class = 0.1 → confidence = 0.09</pre><p>A high class score alone is not sufficient.</p><h4>What this confidence is used for</h4><p>This value is the one you should:</p><ul><li>Threshold</li><li>Use for ranking detections</li><li>Pass into NMS</li></ul><p>Not:</p><ul><li>Objectness alone</li><li>Class score alone</li></ul><h4>Typical thresholding</h4><p>A common threshold looks like:</p><pre>if (confidence &lt; conf_threshold)<br>    continue;</pre><p>Typical values:</p><ul><li>0.2 – 0.3 → more detections</li><li>0.4 – 0.5 → fewer, cleaner detections</li></ul><p>After computing confidence, the next step is to <strong>filter low-quality candidates before running NMS</strong>. This ordering is important for both correctness and performance.</p><h4>Thresholding and NMS Order</h4><p>Once the final confidence score is computed, the next step is <strong>filtering</strong>.</p><p>This step is applied <strong>before</strong> Non-Maximum Suppression (NMS).</p><h4>Why thresholding comes first</h4><p>NMS is an expensive operation.</p><p>Its complexity grows with the number of candidate boxes:</p><pre>O(n²)</pre><p>Thresholding early:</p><ul><li>Removes low-quality predictions</li><li>Reduces the number of boxes passed to NMS</li><li>Improves performance significantly</li></ul><h4>Correct order of operations</h4><p>The correct post-processing flow is:</p><pre>YOLO raw output<br>   ↓<br>Decode box + class<br>   ↓<br>confidence = objectness × class_score<br>   ↓<br>Threshold (filter)<br>   ↓<br>NMS (remove duplicates)<br>   ↓<br>Final detections</pre><h4>Common mistake</h4><p>Running NMS before thresholding.</p><p>This:</p><ul><li>Slows down inference</li><li>Produces unstable results</li><li>Wastes computation on background predictions</li></ul><p>Before wrapping up, it’s important to mention <strong>model variations</strong> that can affect how this output tensor should be interpreted.</p><h4>Important Variation: YOLOv8 Output Format</h4><p>Not all YOLO ONNX exports follow the same output layout.</p><p>Some <strong>YOLOv8</strong> models remove the explicit objectness score and output:</p><pre>[x, y, w, h, cls0, cls1, ...]</pre><p>In this case:</p><ul><li>There is <strong>no separate objectness value</strong></li><li>Class scores already represent final confidence</li></ul><h4>Why this matters</h4><p>Assuming the wrong layout will lead to:</p><ul><li>Incorrect confidence computation</li><li>Invalid filtering</li><li>Broken detections</li></ul><p>This is why you should <strong>never assume the output format</strong>.</p><h4>What to always check</h4><p>Before writing decoding logic:</p><ol><li>Print the output tensor shape</li><li>Check the value of C</li><li>Inspect the first row of the output tensor</li></ol><p>These steps immediately reveal:</p><ul><li>Whether objectness is present</li><li>Where class scores start</li><li>How many values exist per box</li></ul><h4>Debug tip</h4><p>A simple inspection loop is often enough:</p><pre>for (int j = 0; j &lt; elements_per_box; j++)<br>    std::cout &lt;&lt; data[j] &lt;&lt; &quot; &quot;;</pre><p>This helps confirm:</p><ul><li>Value ranges</li><li>Layout correctness</li><li>Normalization behavior</li></ul><p>With the tensor decoded and confidence computed, we can summarize the core ideas that make YOLO post-processing work correctly.</p><p>By now, you should have a clear picture of what happens after session.Run() in YOLO inference. The model has done its work, producing a large tensor of raw predictions — it’s just up to us to interpret it.</p><p>Decoding these predictions in C++ is straightforward once you understand the tensor shape, memory layout, and how objectness interacts with class probabilities. Filtering low-confidence boxes and applying NMS turns this raw output into clean, usable detections.</p><p>Getting this step right removes most of the common headaches: misplaced boxes, weird confidence scores, and inconsistent results. Once the decoding logic is in place, everything downstream from drawing boxes on an image to integrating YOLO into a larger application becomes predictable and reliable.</p><p>If you’d like to connect, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acc39db0a676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Pixels to Tensors: YOLO Preprocessing Explained for ONNX Runtime]]></title>
            <link>https://isvidhi.medium.com/from-pixels-to-tensors-yolo-preprocessing-explained-for-onnx-runtime-45eac60fd205?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/45eac60fd205</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 15:22:25 GMT</pubDate>
            <atom:updated>2026-01-08T15:30:43.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*C3lhqsmR4mnanJLvyJnGzw.png" /></figure><p>In my previous blog, I broke down <strong>ONNX Runtime from the inside out </strong>sessions, execution providers, memory, and how inference actually runs.</p><p>But there’s a critical step <em>before</em> ONNX Runtime ever touches your model <strong>preprocessing</strong>.</p><p>Your model does not understand images. It only understands tensors.</p><p>This blog answers one deceptively simple but extremely important question: <strong>How do you convert a real-world image into <em>exactly</em> the tensor the YOLO model was trained on?</strong></p><p>Because if preprocessing is even slightly wrong, inference still runs but the outputs are pure garbage.</p><h3>What problem does preprocessing solve?</h3><p>Your model <strong>does not understand images</strong>. It only understands <strong>tensors</strong>. Preprocessing answers this question:</p><blockquote><strong><em>How do I convert a real image into exactly the tensor the model was trained on?</em></strong></blockquote><h3>High-level YOLO preprocessing pipeline</h3><p>Almost all YOLO models expect this:</p><pre>cv::Mat (BGR, HxWx3, uint8)<br>  ↓<br>Resize (with or without letterbox)<br>  ↓<br>Color conversion (BGR → RGB)<br>  ↓<br>Normalize (0–255 → 0–1)<br>  ↓<br>Layout change (HWC → CHW)<br>  ↓<br>Batch dimension (1,3,H,W)<br>  ↓<br>float32 tensor</pre><p>We’ll break <strong>each step deeply</strong>, like we did with ORT components.</p><h3>Step 1: Understand the model’s expected input</h3><p>Before touching OpenCV, you must know:</p><h4>1. Input shape</h4><p>From Ort::Session inspection:</p><pre>[1, 3, 640, 640]</pre><p>Meaning:</p><ul><li>Batch = 1</li><li>Channels = 3</li><li>Height = 640</li><li>Width = 640</li></ul><h4>2. Data type</h4><pre>float32</pre><h4>3. Color order</h4><pre>RGB</pre><p>YOLO <strong>does not expect BGR</strong>.</p><h3>Step 2: Read image (OpenCV reality check)</h3><pre>cv::Mat image = cv::imread(&quot;test.jpg&quot;);</pre><p>OpenCV gives:</p><ul><li>Format: BGR</li><li>Type: uint8</li><li>Layout: HWC</li></ul><p>Example:</p><pre>[H, W, 3] uint8</pre><p>This is <strong>completely incompatible</strong> with the model.</p><h3>Step 3: Resize (VERY IMPORTANT)</h3><h4>Why resize?</h4><p>YOLO expects <strong>fixed spatial dimensions</strong>.</p><pre>cv::resize(image, resized, cv::Size(640, 640));</pre><p>Now:</p><pre>[640, 640, 3]</pre><p>⚠️ This <strong>distorts aspect ratio</strong></p><h3>Step 4: Color conversion (BGR → RGB)</h3><p>This step is <strong>non-negotiable</strong>.</p><pre>cv::cvtColor(resized, rgb, cv::COLOR_BGR2RGB);</pre><p>Why?</p><ul><li>OpenCV loads BGR</li><li>YOLO trained on RGB</li></ul><p>Wrong color → wrong detections.</p><h3>Step 5: Convert to float &amp; normalize</h3><p>YOLO expects values in:</p><pre>[0.0, 1.0]</pre><h4>Why normalization matters</h4><p>During training:</p><ul><li>Model learned on normalized inputs</li><li>Feeding raw 0–255 breaks scale assumptions</li></ul><h4>Code</h4><pre>rgb.convertTo(float_img, CV_32F, 1.0 / 255.0);</pre><p>Now:</p><ul><li>Type: float</li><li>Range: [0,1]</li></ul><h3>Step 6: Layout change (HWC → CHW)</h3><p>Current layout:</p><pre>HWC → [640][640][3]</pre><p>Model expects:</p><pre>CHW → [3][640][640]</pre><h4>Why CHW?</h4><p>ONNX models (from PyTorch) use: Channels first, better memory access for convolution</p><h4>How to convert in OpenCV</h4><h4>Split channels</h4><pre>std::vector&lt;cv::Mat&gt; channels(3);<br>cv::split(float_img, channels);</pre><p>Now:</p><ul><li>channels[0] → R</li><li>channels[1] → G</li><li>channels[2] → B</li></ul><p>Each:</p><pre>[640][640]</pre><h3>Step 7: Flatten into continuous buffer</h3><h3>What ONNX Runtime expects</h3><p>ONNX Runtime does <strong>not</strong> acceptcv::Mat, separate channel matrices, 2D images. It accepts:</p><blockquote><strong><em>One flat, contiguous block of memory</em></strong></blockquote><p>So our job is to turn 3 separate cv::Mat channels (H×W) into 1D array:<br>[3 × H × W].</p><h3>What we have before this step</h3><p>After splitting + normalization, you have:</p><pre>channels[0] → R (640×640, float)<br>channels[1] → G (640×640, float)<br>channels[2] → B (640×640, float)</pre><p>This is <strong>where preprocessing meets ORT</strong>.</p><pre>std::vector&lt;float&gt; input_tensor_values;<br>input_tensor_values.reserve(3 * 640 * 640);</pre><p>This vector will become: [ 3 * 640 * 640 floats ]<br>Now we iterate <strong>channel by channel</strong>, not pixel by pixel.</p><pre>for (int c = 0; c &lt; 3; c++) {<br>    input_tensor_values.insert(<br>        input_tensor_values.end(),<br>        (float*)channels[c].datastart,<br>        (float*)channels[c].dataend<br>    );<br>}</pre><h4>After loop runs</h4><p>Iteration 0 (c = 0):</p><pre>vector = [ r1 r2 r3 ... rN ]</pre><p>Iteration 1 (c = 1):</p><pre>vector = [ r1 ... rN g1 ... gN ]</pre><p>Iteration 2 (c = 2):</p><pre>vector = [ r1 ... rN g1 ... gN b1 ... bN ]</pre><p>Memory layout now:</p><pre>[R channel][G channel][B channel]</pre><p>Exactly: CHW.</p><h3>Step 8: Add batch dimension (conceptual)</h3><p>Batch is <strong>not</strong> a separate buffer step.</p><p>You just define shape as:</p><pre>std::vector&lt;int64_t&gt; input_shape = {1, 3, 640, 640};</pre><p>Your data already matches:</p><pre>1 × (3 × 640 × 640)</pre><h3>Step 9: Create ORT tensor (connects to previous lesson)</h3><pre>Ort::Value input_tensor = Ort::Value::CreateTensor&lt;float&gt;(<br>    memory_info,<br>    input_tensor_values.data(),<br>    input_tensor_values.size(),<br>    input_shape.data(),<br>    input_shape.size()<br>);</pre><p>With preprocessing complete, the natural questions follow: what does CHW actually represent, why is it required by YOLO and ONNX Runtime, and how does letterboxing help preserve aspect ratio without distorting detections?</p><p>The remainder of this post breaks down these concepts in detail.</p><h3>What CHW actually means</h3><p>For an image tensor:</p><pre>C = Channels (RGB)<br>H = Height<br>W = Width</pre><p>So:</p><pre>CHW = [3, H, W]</pre><p>Example:</p><pre>RGB image → [3, 640, 640]</pre><h3>The alternative (HWC)</h3><p>What OpenCV gives you:</p><pre>HWC = [H, W, 3]</pre><p>Example:</p><pre>[640, 640, 3]</pre><p>So the question is:</p><blockquote><em>Why do ML frameworks prefer CHW, while image libraries prefer HWC?</em></blockquote><h3>1. Convolution explains everything</h3><p>Convolution is the <strong>core operation</strong> in CNNs.</p><p>A convolution kernel looks like:</p><pre>[out_channels, in_channels, kH, kW]</pre><p>For one output pixel: It combines <strong>all input channels together, a</strong>t the <strong>same spatial location</strong></p><h4>With CHW layout:</h4><pre>C dimension is contiguous in memory</pre><p>So convolution can: Read all channels together, do vectorized math (SIMD), use CPU cache efficiently therefore l<strong>ess memory jumping</strong></p><h4>With HWC layout: Channels are <strong>spread apart in memory</strong></h4><pre>R G B | R G B | R G B | ...</pre><p>Convolution has to: Jump memory addresses, break cache locality, do more loads making it slower for math-heavy ops</p><h3>2. Memory locality (very important)</h3><h4>CHW memory layout looks like:</h4><pre>RRRRRRR<br>GGGGGGG<br>BBBBBBB</pre><p>Each channel is a <strong>dense block</strong>.</p><h4>HWC memory layout:</h4><pre>RGB RGB RGB RGB</pre><p>Better for: Display and pixel-wise access</p><p>Worse for: Matrix multiplication and convolution</p><p>Deep learning is <strong>math-heavy</strong>, not pixel-by-pixel.</p><h3>3. BLAS / GEMM compatibility</h3><p>Under the hood: Convolutions → matrix multiplications (GEMM) , GEMM libraries expect <strong>channel-major layouts</strong></p><p>CHW maps cleanly to:</p><pre>[Channels × (H × W)]</pre><p>This is why:</p><ul><li>ONNX</li><li>PyTorch</li><li>Caffe</li><li>ONNX Runtime</li></ul><p>All standardize on <strong>NCHW</strong>.</p><h3>4. CPU &amp; GPU vectorization</h3><h4>SIMD (CPU)</h4><p>SIMD instructions work best when: Data is contiguous and same operation is repeated.</p><p>CHW allows: Vector loads, fused multiply-add, cache-friendly access</p><h4>GPU</h4><p>CUDA kernels are written assuming: Channel-first tensors, coalesced memory access</p><h3>Why OpenCV uses HWC (contrast)</h3><p>OpenCV is for Image processing, visualization, pixel operations</p><p>HWC is perfect when you process one pixel at a time, you want RGB values together</p><p>So, OpenCV → HWC &amp; ONNX / DL → CHW</p><p><strong>ONNX uses CHW because convolution, vectorization, cache usage, and hardware acceleration all work best with channel-first data.</strong></p><h4>What “batch” really means?</h4><p><strong>In the the 8th step we discussed about batch.<br>Batch = how many samples you process together</strong></p><ul><li>Batch = 1 → one image</li><li>Batch = N → N images stacked together</li></ul><p>Importantly:</p><blockquote><em>Batch does NOT change pixel layout inside one image</em></blockquote><h3>What you already have in memory</h3><p>From Step 7, your buffer is:</p><pre>[R][G][B]</pre><p>Flattened as:</p><pre>3 × 640 × 640 floats</pre><p>This is already:</p><pre>1 × (3 × 640 × 640)</pre><p>So batch = 1 is <strong>implicitly there</strong>.</p><h3>Why ONNX still needs the batch dimension</h3><p>ONNX models are trained with input shape:</p><pre>[N, C, H, W]</pre><p>Even if N = 1, the dimension <strong>must exist</strong>.</p><p>So you declare:</p><pre>std::vector&lt;int64_t&gt; input_shape = {1, 3, 640, 640};</pre><p>This tells ONNX Runtime:</p><blockquote><em>“This buffer represents 1 image, with 3 channels, height 640, width 640.”</em></blockquote><p>Think of memory as a long strip of numbers</p><p>Shape is instructions on how to group those numbers</p><p>Batch dimension = “group this strip into <strong>1 image</strong>”.</p><h3>What happens if batch &gt; 1 (for understanding)</h3><p>If batch = 2:</p><p>Shape:</p><pre>{2, 3, 640, 640}</pre><p>Memory layout must be:</p><pre>[Img1_R][Img1_G][Img1_B][Img2_R][Img2_G][Img2_B]</pre><p>Now batch <strong>does</strong> affect memory size.</p><p>But for batch = 1: , <em>It’s just a label.</em></p><h3>How this fits into tensor creation</h3><pre>Ort::Value input_tensor = Ort::Value::CreateTensor&lt;float&gt;(<br>    memory_info,<br>    input_tensor_values.data(),<br>    input_tensor_values.size(),<br>    input_shape.data(),<br>    input_shape.size()<br>);</pre><ul><li>input_tensor_values → actual data</li><li>input_shape → interpretation</li><li>Batch dimension lives <strong>only in </strong><strong>input_shape</strong></li></ul><h3>Final mental picture</h3><pre>Memory:  [ R ][ G ][ B ]<br>Shape:   [ 1 ][ 3 ][ 640 ][ 640 ]</pre><h4>Why letterboxing exists</h4><p>YOLO models are trained on <strong>fixed-size square inputs</strong> (e.g. 640×640). But real images are rectangular and arbitrary aspect ratios, if you simply resize:</p><pre>1280×720 → 640×640</pre><p>You <strong>distort objects</strong>. Letterboxing solves this by:</p><blockquote><em>Preserving aspect ratio while fitting into model input</em></blockquote><h4>What letterboxing does (conceptually)</h4><p>Given:</p><pre>Original image: W×H<br>Target size:    S×S (e.g. 640×640)</pre><p>Letterboxing:</p><ol><li>Scales image <strong>uniformly</strong></li><li>Pads remaining space with a constant color</li><li>Centers the image</li></ol><h4>Visual intuition</h4><pre>+----------------------+<br>|      padding         |<br>|   +------------+     |<br>|   |   image    |     |<br>|   |            |     |<br>|   +------------+     |<br>|      padding         |<br>+----------------------+</pre><p>After letterboxing: image is exactly 640×640, aspect ratio preserved and the objects are not distorted</p><p>Preprocessing is not a cosmetic step it is part of the model.</p><p>YOLO was trained on tensors with a specific shape, layout, scale, and memory order. When inference works, it’s not because ONNX Runtime is forgiving it’s because your input <em>matches the training contract exactly</em>.</p><p>Once you understand CHW, batch dimensions, normalization, and letterboxing, preprocessing stops being magic and becomes deterministic engineering.</p><p>If you’ve read my previous deep dive on ONNX Runtime and this post on preprocessing, you now understand <strong>both sides of inference</strong>: how data enters the model and how the runtime executes it. That’s the difference between models that “run” and models that actually work.</p><p>If you’d like to connect or discuss ONNX / inference optimization, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45eac60fd205" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying ONNX Runtime: The Inference Engine Behind Your ONNX Models]]></title>
            <link>https://isvidhi.medium.com/onnx-runtime-under-the-hood-how-onnx-models-actually-run-in-production-72290e8182c4?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/72290e8182c4</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 15:36:00 GMT</pubDate>
            <atom:updated>2026-01-06T15:43:29.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*IWQiQHuuwfGXa6_g7yWJyg.png" /></figure><p>If you’ve ever trained a deep learning model, you probably know that getting good accuracy is only part of the job. The real headache often starts when you try to actually run that model somewhere maybe in a C++ app, on a server, or even on an edge device.</p><p>This is where I personally found <strong>ONNX</strong> really useful. ONNX gives you a common format to export models from frameworks like <strong>PyTorch</strong> or <strong>TensorFlow</strong> so you’re not locked into one ecosystem. But exporting the model is still not the end of the story you need something that can run that model efficiently.</p><p>That “something” is <strong>ONNX Runtime (ORT)</strong>.</p><p>ONNX Runtime is basically the engine that takes your .onnx file and figures out how to execute it fast. It handles things like graph optimizations, memory management, and even deciding whether to run parts of the model on CPU, GPU, or other accelerators.</p><p>When I first started using ORT, I treated it like a black box: load model, pass input, get output. It works but a lot of things don’t make sense until you understand what’s going on under the hood. Things like why inference is slow, why outputs look weird, or why switching execution providers suddenly changes behavior.</p><p>So in this first post, instead of jumping straight into inference code, I want to break down the main components of ONNX Runtime and how they fit together. Once these pieces are clear, the actual inference pipeline becomes much easier to reason about especially when working with C++ and OpenCV.</p><p>Let’s go through these components one by one, in the same order they are involved during inference.</p><h3>Where ONNX Runtime fits in the pipeline</h3><p>Think of the whole detection pipeline like this:</p><pre>Image<br>  ↓<br>[ Preprocessing ]   ← resize, normalize, CHW, batch<br>  ↓<br>[ ONNX Runtime ]    ← THIS STEP<br>  ↓<br>Raw Output Tensors<br>  ↓<br>[ Output Decoding ] ← boxes, scores, classes<br>  ↓<br>[ NMS ]             ← remove duplicates<br>  ↓<br>Final Detections</pre><p>Right now we focus only on: <strong>ONNX Runtime</strong></p><h3>ONNX Runtime Component 1: Ort::Env</h3><h4>What problem does Ort::Env solve?</h4><p>Before ONNX Runtime can do anything, it needs:</p><ul><li>A global runtime context</li><li>Logging configuration</li><li>Thread pools</li><li>Internal state initialization</li></ul><p>Ort::Env is that global runtime object.</p><p>Think of it as:</p><blockquote><em>“Starting the ONNX Runtime engine”</em></blockquote><p>No Env → no inference → nothing works.</p><h4>How many Ort::Env objects should exist?</h4><p><strong>Exactly one per process</strong> (best practice) you can create more, but it is wasteful and no benefit for YOLO inferencing. Therefore:</p><pre>int main() {<br>    Ort::Env env(...);  // ONE TIME<br>    // everything else uses this<br>}</pre><h4>Constructor</h4><pre>Ort::Env env(ORT_LOGGING_LEVEL_WARNING, &quot;yolo&quot;);</pre><ul><li><strong>Parameter 1</strong>: Logging Level</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*5qUgTvc9Aa0Jmd19DoNRvQ.png" /></figure><ul><li><strong>Parameter 2</strong>: Log ID (name)</li></ul><p>&quot;yolo&quot;this is a tag for logs, helps identify runtime messages.</p><h3>ONNX Runtime Component 2: Ort::SessionOptions</h3><p>SessionOptions is where ONNX Runtime starts to feel powerful, not just boilerplate.</p><h4>What problem does SessionOptions solve?</h4><p>You already have:</p><ul><li>Ort::Env → runtime exists</li></ul><p>Now you need to answer:</p><blockquote><strong><em>“How should this model run?”</em></strong></blockquote><p>That includes:</p><ul><li>Optimizations</li><li>Threads</li><li>CPU vs GPU</li><li>Performance vs determinism</li></ul><p>Ort::SessionOptions answers how inference is executed.</p><h4>Minimal required usage (baseline)</h4><pre>Ort::SessionOptions session_options;<br>session_options.SetGraphOptimizationLevel(<br>    GraphOptimizationLevel::ORT_ENABLE_ALL<br>);</pre><p>This alone already improves YOLO inference speed.</p><h4>2.1 Graph Optimization Level (MOST IMPORTANT)</h4><p>What is graph optimization?</p><p>ONNX models are computation graphs.</p><p>ONNX Runtime:</p><ul><li>Fuses ops</li><li>Removes redundancies</li><li>Reorders nodes</li><li>Simplifies subgraphs</li></ul><p>Available levels:</p><ul><li>ORT_DISABLE_ALL</li><li>ORT_ENABLE_BASIC</li><li>ORT_ENABLE_EXTENDED</li><li>ORT_ENABLE_ALL</li></ul><p>For YOLO: <strong>Always use </strong><strong>ORT_ENABLE_ALL</strong></p><pre>session_options.SetGraphOptimizationLevel(<br>    GraphOptimizationLevel::ORT_ENABLE_ALL<br>);</pre><p>This can give noticeable speedup.</p><h4>2.2 Threading Control (CPU inference)</h4><p>Threading matters when running on CPU, batch size &gt; 1 or large images.</p><p><strong>Intra-op threads</strong><br>Parallelism inside an operator. You have one big task (e.g. convolution on an image) and you split that single task among multiple people.</p><pre>session_options.SetIntraOpNumThreads(4);</pre><p><strong>Inter-op threads</strong><br>Parallelism between operators, instead of splitting one task you try to run multiple tasks at once.</p><pre>session_options.SetInterOpNumThreads(1);</pre><p>Why is this often set to 1?</p><p>Because:</p><ul><li>YOLO layers are mostly sequential</li><li>One op depends on the output of the previous</li><li>Parallelizing them causes context switching overhead</li></ul><p>Typical YOLO CPU config</p><pre>session_options.SetIntraOpNumThreads(4);<br>session_options.SetInterOpNumThreads(1);</pre><p>Rules of thumb:</p><ul><li>IntraOp ≈ number of cores</li><li>InterOp = 1 (usually best)</li></ul><h4>2.3 Execution Mode</h4><pre>session_options.SetExecutionMode(<br>    ExecutionMode::ORT_SEQUENTIAL<br>);</pre><p><strong>ORT_SEQUENTIAL — What it means:</strong><br>Run one operator at a time, next op starts only after previous finishes</p><p><strong>ORT_PARALLEL — What it tries to do:</strong><br>Look at the graph if two operators are independent, run them together</p><p>For YOLO: Stick to SEQUENTIAL, PARALLEL rarely helps for single inference</p><h4>2.4 Execution Providers (EPs)</h4><p>This is where CPU vs GPU is decided.</p><p><strong>Default behavior</strong><br>If you do nothing: CPU execution provider is used</p><p>Execution providers are configured through SessionOptions, not Env.</p><h4>2.5 Memory pattern optimization</h4><pre>session_options.EnableMemPattern();</pre><p>What problem does this solve?</p><p>During inference:</p><ul><li>Tensors are created</li><li>Used</li><li>Destroyed again and again for every frame</li></ul><p>What ONNX Runtime does with Memory Patterns</p><p>Think of inference like this:</p><p><strong>First run</strong><br>ONNX Runtime:</p><ul><li>Watches how much memory is needed</li><li>Notes which buffers can be reused</li><li>Builds a memory layout plan</li></ul><p><strong>Next runs:</strong></p><ul><li>Reuses the same memory blocks</li><li>No repeated malloc / free</li><li>Just overwrite values</li></ul><h4>2.6 Profiling (debug / learning)</h4><p>Profiling = measuring where time is actually spent</p><pre>session_options.EnableProfiling(&quot;yolo_profile.json&quot;);</pre><p>This saves detailed timing info, shows slow ops extremely useful for optimization</p><h3>ONNX Runtime Component 3: Ort::Session</h3><h4>What problem does Ort::Session solve?</h4><p>You have:</p><ul><li>Ort::Env → runtime exists</li><li>Ort::SessionOptions → how inference should run</li></ul><p>Now you need: An object that loads the ONNX model and can execute it</p><p>That object is Ort::Session.</p><h3>What exactly is Ort::Session?</h3><p>Ort::Session represents:</p><ul><li>A loaded .onnx model</li><li>An optimized computation graph</li><li>A ready-to-run inference engine</li></ul><p>Think of it as:</p><blockquote><em>A compiled, executable version of your ONNX model</em></blockquote><h4>Creating a Session (anatomy)</h4><pre>Ort::Session session(env, &quot;yolo.onnx&quot;, session_options);</pre><p>What happens internally here?</p><p>When this line runs:</p><ul><li>ONNX file is parsed</li><li>Graph is validated</li><li>Optimizations are applied</li><li>Execution provider is selected (CPU by default)</li><li>Memory planning is done</li></ul><p>⚠️ This is expensive, do it once never inside a loop</p><p>Rule:</p><blockquote><em>Session must live shorter than </em><em>Env</em></blockquote><p>Correct order:</p><pre>Ort::Env env(...);<br>Ort::Session session(env, ...);</pre><p>When env dies → session becomes invalid.</p><h4>What can you do with Ort::Session?</h4><p>Three main things:</p><ul><li>Inspect model metadata</li><li>Query inputs &amp; outputs</li><li>Run inference</li></ul><h4>Inspecting Inputs &amp; Outputs</h4><p><strong>Number of inputs</strong></p><pre>size_t num_inputs = session.GetInputCount();</pre><p><strong>Getting input name</strong></p><pre>Ort::AllocatorWithDefaultOptions allocator;<br>char* input_name = session.GetInputName(0, allocator);</pre><p>Example:</p><pre>&quot;images&quot;</pre><p>⚠️ Memory note:</p><ul><li>ONNX Runtime allocates the string</li><li>You must free it using allocator</li></ul><p><strong>Getting input shape</strong></p><pre>Ort::TypeInfo type_info = session.GetInputTypeInfo(0);<br>auto tensor_info = type_info.GetTensorTypeAndShapeInfo();<br>std::vector&lt;int64_t&gt; input_shape = tensor_info.GetShape();</pre><p>Typical YOLO input:</p><pre>[1, 3, 640, 640]</pre><p>Dynamic shapes may show:</p><pre>[-1, 3, 640, 640]</pre><h4>Output Inspection</h4><p>Same process:</p><pre>size_t num_outputs = session.GetOutputCount();<br>char* output_name = session.GetOutputName(0, allocator);</pre><h4>Running Inference (conceptually)</h4><pre>session.Run(<br>    Ort::RunOptions{nullptr},<br>    input_names,<br>    input_tensors,<br>    num_inputs,<br>    output_names,<br>    num_outputs<br>);</pre><p>What happens:</p><ul><li>Input tensor is fed</li><li>Graph executes</li><li>Output tensors are produced</li></ul><p>No training. No gradients.</p><h3>ONNX Runtime Component 4: Ort::MemoryInfo</h3><p>Ort::MemoryInfo is a descriptor that tells ONNX Runtime:</p><blockquote><em>“This tensor’s data is stored here, allocated like this, and should be accessed in this way.”</em></blockquote><p>It does <strong>not</strong> hold data. It only describes the memory.</p><h4>The most common MemoryInfo (CPU)</h4><pre>Ort::MemoryInfo memory_info =<br>    Ort::MemoryInfo::CreateCpu(<br>        OrtArenaAllocator,<br>        OrtMemTypeDefault<br>    );</pre><p>This means:</p><ul><li><strong>Allocator type</strong><br>OrtArenaAllocator – ORT-managed CPU allocator</li><li><strong>Memory type</strong><br>OrtMemTypeDefault – Normal CPU memory</li></ul><p>This is what you will use <strong>90% of the time for YOLO</strong>.</p><h4>Why can’t ORT guess this automatically?</h4><p>Because you might pass:</p><ul><li>std::vector&lt;float&gt;</li><li>new[]</li><li>OpenCV buffer</li><li>GPU pointer</li></ul><p>ORT must be told:</p><blockquote><em>“This pointer is valid CPU memory, laid out normally”</em></blockquote><p>Then this memory_info is used to wrap your buffer into a tensor.</p><h4>Important ownership rule (VERY IMPORTANT)</h4><p><strong>ONNX Runtime does NOT own your buffer</strong></p><p>When you create a tensor using your memory:</p><ul><li>You own the memory</li><li>It must remain valid during inference</li></ul><p><strong>Wrong:</strong></p><pre>{<br>    std::vector&lt;float&gt; temp;<br>    Ort::Value tensor = Ort::Value::CreateTensor(..., temp.data(), ...);<br>}</pre><p>temp destroyed → tensor invalid</p><p><strong>Correct:</strong></p><pre>std::vector&lt;float&gt; input;<br>Ort::Value tensor = Ort::Value::CreateTensor(...);</pre><p>input lives long enough</p><h3>ONNX Runtime Component 5: Ort::Value</h3><h4>Why Ort::Value exists</h4><p>ONNX Runtime only understands ONNX values, not C++ types. ORT needs all of that wrapped into one universal container. That container is Ort::Value.</p><h4>What exactly is Ort::Value?</h4><p>Ort::Value is a variant type that can represent:</p><ul><li>Tensor</li><li>Sequence</li><li>Map</li><li>Optional</li></ul><p>For YOLO inference:</p><blockquote><em>You will use </em><em>Ort::Value as a </em><strong><em>Tensor</em></strong><em>, always</em></blockquote><h4>How tensor creation really works (big picture)</h4><pre>Your memory (float*)<br>        ↓<br>MemoryInfo (describes it)<br>        ↓<br>Ort::Value (wraps it as tensor)<br>        ↓<br>session.Run()</pre><p>ORT does <strong>not copy your data by default</strong>.</p><h4>Creating a CPU tensor (YOLO-style)</h4><p><strong>Step 1: Your data buffer</strong></p><pre>std::vector&lt;float&gt; input_tensor_values(<br>    1 * 3 * 640 * 640<br>);</pre><p><strong>Step 2: Shape definition</strong></p><pre>std::vector&lt;int64_t&gt; input_shape = {1, 3, 640, 640};</pre><p>Important:</p><ul><li>Shape must match model input</li><li>Use int64_t, not int</li></ul><p><strong>Step 3: MemoryInfo (already learned)</strong></p><pre>Ort::MemoryInfo memory_info =<br>    Ort::MemoryInfo::CreateCpu(<br>        OrtArenaAllocator,<br>        OrtMemTypeDefault<br>    );</pre><p><strong>Step 4: Create </strong><strong>Ort::Value tensor</strong></p><pre>Ort::Value input_tensor = Ort::Value::CreateTensor&lt;float&gt;(<br>    memory_info,<br>    input_tensor_values.data(),<br>    input_tensor_values.size(),<br>    input_shape.data(),<br>    input_shape.size()<br>);</pre><p>Now:</p><ul><li>ORT sees this as a valid input tensor</li><li>No data copied</li><li>Pointer must remain valid</li></ul><h4>Output tensors are also Ort::Value</h4><p>After inference:</p><pre>auto output_tensors = session.Run(...);</pre><p>Each output:</p><pre>Ort::Value&amp; output = output_tensors[0];</pre><p>This is also an Ort::Value but owned by ORT.</p><h4>Accessing output tensor data</h4><pre>float* output_data = output.GetTensorMutableData&lt;float&gt;();</pre><p>Now you can:</p><ul><li>Read boxes</li><li>Decode predictions</li></ul><p>At this point, we’ve covered everything that ONNX Runtime actually touches during inference from the moment the runtime starts, to the moment raw output tensors are handed back to you.</p><p>The important takeaway is this: <strong>ONNX Runtime is not a black box</strong>.<br> It is a well-structured system with clearly defined responsibilities:</p><ul><li>Ort::Env initializes the runtime</li><li>Ort::SessionOptions defines <em>how</em> inference should run</li><li>Ort::Session loads and optimizes the model</li><li>Ort::MemoryInfo explains <em>where</em> your data lives</li><li>Ort::Value is the bridge between your C++ memory and the ONNX world.</li></ul><p>Most ONNX Runtime issues aren’t “model problems” they’re <strong>pipeline understanding problems</strong>.</p><p>In the next post, we’ll build on this foundation and walk through a <strong>complete YOLO inference pipeline in C++ with OpenCV</strong>, step by step preprocessing, tensor creation, running the session, and decoding outputs correctly.</p><p>I work on deploying deep learning models in production using C++, OpenCV, and ONNX Runtime.</p><p>If you’d like to connect or discuss ONNX / inference optimization, you can find me on <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/isvidhi/">https://www.linkedin.com/in/isvidhi/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72290e8182c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Image Processing: 5 Essential Techniques Every Beginner Should Know]]></title>
            <link>https://isvidhi.medium.com/getting-started-with-image-processing-5-essential-techniques-every-beginner-should-know-6e2a573fec87?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2a573fec87</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 17:10:57 GMT</pubDate>
            <atom:updated>2025-11-05T15:17:25.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjWO5IHejvv-P7xEJQdZ6g.png" /></figure><p>Image processing is everywhere from improving your phone’s camera photos to enabling self-driving cars to understand the world around them.<br> At its core, it’s about taking an image and performing operations that make it more useful enhancing it, analyzing it, or extracting information from it.</p><p>In simpler terms:</p><blockquote><strong><em>Image processing is how we teach computers to “see” by manipulating pixels.</em></strong></blockquote><p>Before computers can recognize faces, read text from a picture, or detect objects, the images often need to be cleaned, simplified, and transformed. That’s what image processing does, it prepares the image for intelligent decision-making.</p><p>In this post, we’ll look at <strong>five essential image processing techniques</strong> every beginner should learn, and we’ll implement each one in <strong>C++ using OpenCV</strong>, one of the most popular computer vision libraries.</p><h3>1️⃣ Grayscale Conversion — Simplifying the Image</h3><p>A color image is made up of three channels: Red, Green, and Blue (RGB).<br>Each pixel contains three values corresponding to these colors. While color is useful, it’s not always necessary especially when we’re more interested in <em>structure</em> than <em>appearance</em>.</p><p><strong>Grayscale conversion</strong> reduces an image to a single channel by converting colors into shades of gray, ranging from black (0) to white (255).</p><h3>Why it matters</h3><ul><li>Reduces data complexity from 3 channels to 1.</li><li>Makes algorithms like edge detection and thresholding faster and simpler.</li><li>Helps highlight intensity patterns rather than color differences.</li></ul><h3>Example</h3><pre>Mat img = imread(&quot;image.jpg&quot;);<br>Mat gray;<br>cvtColor(img, gray, COLOR_BGR2GRAY);<br>imshow(&quot;Grayscale&quot;, gray);<br>waitKey(0);</pre><p><strong>When to use:</strong><br> Whenever color isn’t important such as before applying edge detection, thresholding, or morphological operations.</p><h3>2️⃣ Resizing and Cropping — Focusing on What Matters</h3><p>Not all images are captured under the same conditions. They can have different dimensions or contain unwanted regions.<br>That’s where resizing and cropping come in.</p><h3>Resizing</h3><p>Resizing changes the overall image dimensions. This is essential when preparing datasets for machine learning models, which often require images of fixed size.</p><h3>Cropping</h3><p>Cropping lets you cut out a specific portion of the image focusing only on the region of interest (ROI).</p><h3>Why it matters</h3><ul><li>Maintains consistency across input data.</li><li>Saves memory and computation time.</li><li>Helps focus only on relevant details.</li></ul><h3>Example</h3><pre>// Resize<br>Mat resized;<br>resize(img, resized, Size(300, 300));</pre><pre>// Crop<br>Rect roi(50, 50, 200, 200);<br>Mat cropped = img(roi);</pre><p><strong>When to use:</strong></p><ul><li>Resize before passing images to a neural network or ML pipeline.</li><li>Crop when you want to isolate a specific object or area in the image.</li></ul><h3>3️⃣ Noise Reduction — Cleaning the Image</h3><p>Images are rarely perfect. They can have random variations in pixel values known as <strong>noise</strong> caused by low lighting, sensor errors, or environmental conditions.</p><p><strong>Noise reduction (smoothing or blurring)</strong> techniques help remove these unwanted distortions while retaining essential structures.</p><h3>Common Filters</h3><h4>1. Gaussian Blur</h4><p>Applies a weighted average using a Gaussian kernel. It smooths the image while keeping transitions gradual.</p><pre>GaussianBlur(img, blurred, Size(5, 5), 0);</pre><h4>2. Median Blur</h4><p>Replaces each pixel with the median of its neighboring pixels. Particularly good for “salt-and-pepper” noise.</p><pre>medianBlur(img, medianBlurred, 5);</pre><h3>Why it matters</h3><ul><li>Reduces unwanted artifacts that can mislead edge or feature detectors.</li><li>Creates cleaner inputs for further analysis like segmentation or object detection.</li></ul><p><strong>When to use:</strong><br>Before applying edge detection, thresholding, or when images appear grainy.</p><h3>4️⃣ Image Enhancement — Making Details Visible</h3><p>Sometimes, an image isn’t noisy but still <em>lacks clarity</em>.<br>Poor lighting, low contrast, or uneven brightness can make important details invisible. <strong>Image enhancement</strong> techniques improve visibility and balance light levels.</p><h3>Techniques</h3><h4>1. Adjusting Brightness and Contrast</h4><p>Brightness shifts all pixel values, while contrast stretches the difference between light and dark regions.</p><pre>img.convertTo(enhanced, -1, 1.2, 30); // alpha=1.2, beta=30</pre><h4>2. Histogram Equalization</h4><p>This technique redistributes intensity values so that all brightness levels appear more evenly.<br>It’s particularly effective for low-light or high-contrast images.</p><pre>cvtColor(img, gray, COLOR_BGR2GRAY);<br>equalizeHist(gray, equalized);</pre><h3>Why it matters</h3><ul><li>Enhances important features for analysis.</li><li>Balances illumination issues.</li><li>Improves results for feature extraction and segmentation.</li></ul><p><strong>When to use:</strong><br> Whenever an image looks dull, dark, or unevenly lit.</p><h3>5️⃣ Edge Detection — Finding the Structure</h3><p>Edges represent sudden intensity changes — essentially, the outlines of objects.<br> Detecting edges helps computers understand the <em>shape</em> and <em>structure</em> of what’s inside an image.</p><h3>Canny Edge Detection</h3><p>One of the most reliable edge detection algorithms. It:</p><ol><li>Removes noise (using Gaussian blur),</li><li>Calculates intensity gradients,</li><li>Traces and connects strong edges.</li></ol><pre>cvtColor(img, gray, COLOR_BGR2GRAY);<br>Canny(gray, edges, 100, 200);<br>imshow(&quot;Edges&quot;, edges);</pre><h3>Why it matters</h3><ul><li>Highlights object boundaries.</li><li>Essential for contour detection, segmentation, and feature extraction.</li></ul><p><strong>When to use:</strong><br> Before tasks like object recognition, shape analysis, or region detection.</p><h3>🧩 Putting It All Together</h3><p>Here’s a simple workflow combining these ideas:</p><ol><li>Convert to grayscale → simplify</li><li>Blur → remove noise</li><li>Detect edges → find structure</li></ol><pre>Mat gray, blurred, edges;<br>cvtColor(img, gray, COLOR_BGR2GRAY);<br>GaussianBlur(gray, blurred, Size(5, 5), 0);<br>Canny(blurred, edges, 100, 200);<br>imshow(&quot;Detected Edges&quot;, edges);</pre><p>The result is a clean outline of the main objects in your image ready for further processing.</p><p>Image processing is like cleaning your lens before taking a photo it prepares data so that further analysis becomes meaningful.</p><p>If you’re learning OpenCV with C++, start by experimenting with these basics.<br> Change kernel sizes, thresholds, and parameters to see how each affects the result that’s where the real understanding begins.</p><p>In the next post, we’ll go a step further into <strong>image segmentation and morphological operations </strong>how to separate objects from the background and refine them pixel by pixel.</p><p>Until then, keep experimenting, one pixel at a time.</p><p>This post is co-authored with <a href="https://medium.com/u/dba1bd4888ce">Ronak Jain</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2a573fec87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to Text Recognition Using Tesseract in C++]]></title>
            <link>https://isvidhi.medium.com/beginners-guide-to-text-recognition-using-tesseract-in-c-d41e96e8c186?source=rss-a40f1ee45706------2</link>
            <guid isPermaLink="false">https://medium.com/p/d41e96e8c186</guid>
            <dc:creator><![CDATA[Vidhi Singhal]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 14:43:34 GMT</pubDate>
            <atom:updated>2025-10-28T14:57:36.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMs1nkpNGAAKmvqD5vZm0A.png" /></figure><p>Want your C++ app to <em>read text from images</em> ?<br>That’s exactly what <strong>Tesseract OCR</strong> does , one of the most popular open-source OCR (Optical Character Recognition) engines maintained by Google. It can analyze an image, detect text regions, and return the recognized words with surprising accuracy all completely free.</p><p>In this guide, you’ll learn how to set up <strong>Tesseract on Windows</strong>, link it with <strong>CMake</strong>, and use it in a <strong>C++ project</strong> to perform real OCR.</p><h3>⚙ Step 1: Setting Up Tesseract OCR on Windows</h3><p>Before writing any code, let’s first install Tesseract and make it accessible to your C++ project.</p><h3>🧩 1. Download and install Tesseract</h3><p>Head over to the official Windows installer:<br> 👉 <a href="https://github.com/UB-Mannheim/tesseract/wiki">https://github.com/UB-Mannheim/tesseract/wiki</a></p><p>Download the latest version (for example, tesseract-ocr-w64-setup.exe) and install it — preferably in a simple location, such as:</p><pre>C:\Tesseract\</pre><p>During installation, make sure the <strong>“Add to PATH”</strong> option is checked — this lets you use Tesseract from anywhere.</p><h3>📁 2. Verify installation</h3><p>Open <strong>Command Prompt</strong> and type:</p><pre>tesseract --version</pre><h3>📦 3. Note the tessdata folder</h3><p>Inside your installation directory, you’ll find:</p><pre>C:\Tesseract\tessdata\</pre><p>This folder contains language files (like eng.traineddata) that Tesseract uses for OCR.</p><h3>🧰 4. Add Tesseract to your CMake project</h3><p>You’ll need to tell CMake where to find the Tesseract and Leptonica libraries.</p><p>In your CMakeLists.txt, add something like:</p><pre>set(Tesseract_INCLUDE_DIR &quot;C:/Tesseract/include&quot;)<br>set(Tesseract_LIBRARY &quot;C:/Tesseract/lib/tesseract.lib&quot;)<br>set(Leptonica_INCLUDE_DIR &quot;C:/Tesseract/include&quot;)<br>set(Leptonica_LIBRARY &quot;C:/Tesseract/lib/liblept.lib&quot;)<br><br>include_directories(${Tesseract_INCLUDE_DIR} ${Leptonica_INCLUDE_DIR})<br>target_link_libraries(OCRDemo PRIVATE ${Tesseract_LIBRARY} ${Leptonica_LIBRARY})</pre><p>Now Tesseract is now installed and linked with your C++ environment.</p><h3>⚙ Step 2: Understanding the Code Step by Step</h3><p>Now that Tesseract is set up, let’s dive into how it actually works inside a C++ program.<br>Here’s a simple example that reads an image, runs OCR on it, and prints the recognized text to the console.</p><pre>#include &lt;QCoreApplication&gt;<br>#include &lt;timeprofiler.h&gt;<br>#include &lt;tesseract/baseapi.h&gt;<br>#include &lt;leptonica/allheaders.h&gt;<br>#include &lt;iostream&gt;<br><br><br>int main() {<br>    tesseract::TessBaseAPI api;<br>    if (api.Init(&quot;C:/Tesseract/tessdata&quot;, &quot;eng&quot;, tesseract::OEM_LSTM_ONLY)) {<br>        std::cerr &lt;&lt; &quot;Could not initialize tesseract.\n&quot;;<br>        return 1;<br>    }<br><br>    Pix* image = pixRead(&quot;path/to/your/image&quot;);  // Replace with your image path<br>    api.SetPageSegMode(tesseract::PSM_AUTO);<br>    api.SetImage(image);<br>    char* outText = api.GetUTF8Text();<br>    std::cout &lt;&lt; &quot;OCR output:\n&quot; &lt;&lt; outText &lt;&lt; std::endl;<br><br>    api.End();<br>    pixDestroy(&amp;image);<br>    delete[] outText;<br><br>    return 0;<br>}</pre><p>We’ll go through this program line by line to understand what’s happening from initializing the Tesseract engine to displaying the image.</p><ol><li><strong>Initializing the OCR engine</strong></li></ol><pre>tesseract::TessBaseAPI api;<br>    if (api.Init(&quot;C:/Tesseract/tessdata&quot;, &quot;eng&quot;, tesseract::OEM_LSTM_ONLY)) {<br>        std::cerr &lt;&lt; &quot;Could not initialize tesseract.\n&quot;;<br>        return 1;<br>    }</pre><p>tesseract::TessBaseAPI apicreates an <strong>instance of Tesseract’s main OCR engine </strong>an object of class TessBaseAPI .</p><pre>if (api.Init(&quot;C:/Tesseract/tessdata&quot;, &quot;eng&quot;, tesseract::OEM_LSTM_ONLY)) {</pre><p>This line <strong>initializes</strong> the OCR engine. <br>&quot;C:/Tesseract/tessdata&quot;→ Path to the folder that contains .traineddata files (like eng.traineddata, hin.traineddata, etc.).<br>These files contain the language model and recognition data that Tesseract uses to read text.</p><p><strong>&quot;eng&quot;</strong>→ Language code. Tells Tesseract to load <strong>English</strong> OCR model (eng.traineddata).</p><p><strong>tesseract::OEM_LSTM_ONLY</strong>→ OCR Engine Mode (OEM).<br> Specifies which OCR engine backend Tesseract should use.<br> There are 4 options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3oTLBc9nlxwM_EiHHZL4g.png" /></figure><p><strong>2. Load the Input Image</strong></p><pre>Pix* image = pixRead(&quot;C:/path/to/image.png&quot;);</pre><p>Pix is a Leptonica image object it’s the internal image format that Tesseract uses. <br>Pix* = pointer to a Leptonica image.</p><p>pixRead() is a <strong>Leptonica function</strong> that:</p><ul><li>Reads an image file (PNG, JPEG, BMP, TIFF, etc.)</li><li>Decodes it</li><li>Returns it as a Pix* object in memory</li></ul><p><strong>3. Set the Image for OCR</strong></p><pre>api.SetImage(image);</pre><p>This line <strong>passes your image</strong> to Tesseract so that it knows what to perform OCR on. api is an instance of tesseract::TessBaseAPI, which manages the whole OCR process. SetImage() accepts a pointer to a Pix image (which you loaded earlier using pixRead() from Leptonica).</p><p><strong>4. Extract Text from the Image</strong></p><pre>char* outText = api.GetUTF8Text();</pre><p>GetUTF8Text() triggers the OCR process internally and returns the recognized text as a dynamically allocated C-style string (char*). The returned text is encoded in <strong>UTF-8</strong>, so it supports all kinds of languages and symbols. There are some other function that you can explore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*Rzcd_9NOKdlNoG0Il_SwJg.png" /></figure><p><strong>5. Display the OCR Result</strong></p><pre>std::cout &lt;&lt; &quot;OCR Output:\n&quot; &lt;&lt; outText &lt;&lt; std::endl;</pre><p><strong>6. Clean Up Resources</strong></p><pre>api.End();           // Shuts down tesseract and releases memory<br>delete[] outText;    // Frees memory used for recognized text<br>pixDestroy(&amp;image);  // Frees the image memory</pre><p>This step ensures you don’t leave any background processes or memory leaks.</p><p><strong>7. Display the Image (Optional)</strong></p><p>If you’re using OpenCV, you can add a few lines to visually confirm which image Tesseract processed:</p><pre>cv::Mat img = cv::imread(&quot;test.png&quot;);<br>cv::imshow(&quot;Input Image&quot;, img);<br>cv::waitKey(0);</pre><p>If everything is set up correctly, running your program should print the extracted text in your console window.</p><p>And there you have it a minimal yet powerful setup to get Tesseract running with C++ on Windows. From here, you can experiment with different fonts, languages, or even preprocess images with OpenCV to boost accuracy. I will be sharing some preprocessing techniques soon.</p><p>If you found this guide helpful or want to chat about computer vision, C++, or OCR projects lets connect on Linkedin -&gt; <a href="https://www.linkedin.com/in/isvidhi">https://www.linkedin.com/in/isvidhi</a></p><p>This post was co-authored with <a href="https://medium.com/u/dba1bd4888ce">Ronak Jain</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d41e96e8c186" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>