<?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 ERGÜN ÇALBAY on Medium]]></title>
        <description><![CDATA[Stories by ERGÜN ÇALBAY on Medium]]></description>
        <link>https://medium.com/@mock3ng?source=rss-c7e1108c407f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zsvpPjRzbWTMbt-E7jz2dw.png</url>
            <title>Stories by ERGÜN ÇALBAY on Medium</title>
            <link>https://medium.com/@mock3ng?source=rss-c7e1108c407f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:03:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mock3ng/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[Using Pytorch Models in C++, Using YOLO Models as Torchscript . Use your model 10x faster]]></title>
            <link>https://medium.com/@mock3ng/using-pytorch-models-in-c-using-yolo-models-as-torchscript-use-your-model-10x-faster-9d50c35a8b5c?source=rss-c7e1108c407f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d50c35a8b5c</guid>
            <dc:creator><![CDATA[ERGÜN ÇALBAY]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 09:59:40 GMT</pubDate>
            <atom:updated>2024-01-18T10:57:38.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>Conversion of YOLO and Pytorch Models to Different Formats and İncreasing the Model Speed to Up To 10 Times Faster for Use of These Formats in C++</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nNC5byCraEfhXM8c" /></figure><p>In the dynamic landscape of machine learning, the transformation of YOLO or PyTorch models into TorchScript has gained prominence, showcasing a methodology that advocates for leveraging these models in C++ rather than Python. This paradigm shift not only brings about improvements in efficiency but also promises a significant boost in execution speed, thereby revolutionizing the way we deploy and utilize deep learning models. As the demand for real-time applications and responsiveness continues to surge, the transition to C++ usage underscores a strategic move toward achieving optimal performance and resource utilization in the realm of computer vision and artificial intelligence. This essay aims to delve into the rationale behind this shift, exploring the intricacies of TorchScript conversion and elucidating the advantages it confers upon applications, ultimately advocating for the adoption of C++ as a preferred environment for deploying YOLO or PyTorch models.</p><p>In this article, we will convert our model into a torchscript model with Python and get our outputs in cpp. These models can be YOLO Models and pytorch models. If you do not have pytorch models, you can convert your models to .pt extension using the pytorch API.</p><p>Loading the YOLO Model and presenting the results in Python :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*qTTeiUzfboM0jlHRt53NKA.png" /></figure><p>Result of using the same model in CPP with torchscript conversion :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*us77aG5ojvRD14jV8fpcEw.jpeg" /></figure><p>We were able to speed it up more than 10 times. Please note that this time includes loading the model into memory.</p><h3>PYTHON CONVERT MODEL :</h3><ol><li><strong>Importing Necessary Libraries:</strong></li></ol><pre>from ultralytics import YOLO<br>import torch<br>import torch.nn as nn<br>import torchvision<br>from time import sleep<br>from torch.utils.mobile_optimizer import optimize_for_mobile</pre><p>In this section, the required libraries and modules are imported. This includes the Ultralytics YOLO library, PyTorch, and related modules.</p><ol><li><strong>Initialization for Model Conversion:</strong></li></ol><pre>imgsize = (1920, 1088)  # Image size must be first height after width!!!</pre><p>Setting the image size as a tuple (height, width) for later use in model conversion.</p><ol><li><strong>Defining </strong><strong>xywh2xyxy Function:</strong></li></ol><pre>def xywh2xyxy(x):<br>    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)<br>    y[..., 0] = x[..., 0] - x[..., 2] / 2  # top left x<br>    y[..., 1] = x[..., 1] - x[..., 3] / 2  # top left y<br>    y[..., 2] = x[..., 0] + x[..., 2] / 2  # bottom right x<br>    y[..., 3] = x[..., 1] + x[..., 3] / 2  # bottom right y<br>    return y</pre><p>This function is designed to modify the coordinate format obtained from the model’s output.</p><ol><li><strong>Defining the </strong><strong>WrapperModel Class:</strong></li></ol><pre>class WrapperModel(torch.nn.Module):<br>    def __init__(self, model: torch.nn.Module):<br>        super().__init__()<br>        self.model = model</pre><pre>    def forward(self, input_tensor: torch.Tensor, conf_thres: float = 0.0):<br>        # Forward pass function, organizes the output, and filters above a certain confidence threshold.<br>        # Then takes the top 30000 objects with the best scores.<br>        # Returns scores, boxes, and classes as output.<br>        # This function serves the purpose of organizing the output of models.</pre><p>A class that organizes the output of the model. This class selects objects with the best scores above a certain confidence threshold.</p><ol><li><strong>Model Conversion and Saving:</strong></li></ol><pre>model = YOLO(&quot;&lt;YOLOMODEL-path&gt;&quot;, task=&quot;detect&quot;)<br>model.export(format=&quot;torchscript&quot;, imgsz=imgsize)</pre><p>Loading the Ultralytics YOLO model and converting it to the specified format (in this case, torchscript).</p><ol><li><strong>Saving the TorchScript Model:</strong></li></ol><pre>torchmodel = torch.load(&quot;/home/cha0/Desktop/cpp/ktscpp/best.torchscript&quot;)  <br>wrapper_model = WrapperModel(torchmodel)<br>scriptedmodel2 = torch.jit.script(wrapper_model)<br>scriptedmodel2.save(&quot;/home/cha0/Desktop/cpp/ktscpp/bestcpp.torchscript&quot;)</pre><p>Saving the model for PyTorch Lite conversion.</p><ol><li><strong>Printing the Results:</strong></li></ol><pre>print(&quot;----------------------- Model Converted! -----------------------&quot;)<br>print(f&quot;Format: torchscript, Image Size= {imgsize}&quot;)<br>print(&quot;Please wait now model converting PyTorch Lite format for Android...&quot;)<br>print(&quot;&quot;)<br>print(&quot;**********************&quot;)<br>print(&quot;&quot;)<br>print(&quot;Please wait....&quot;)<br>print(&quot;&quot;)<br>sleep(3)</pre><p>Informative messages indicating the successful conversion of the model.</p><p>You can convert it for use on cross platforms.</p><ol><li><strong>Converting to PyTorch Lite Format and Saving (Optional):</strong></li></ol><pre>mobilemodel = optimize_for_mobile(scriptedmodel2)  # This option is optional, you can remove it if not needed!<br># mobilemodel._save_for_lite_interpreter(&quot;&lt;&gt;&quot;)</pre><p>Optionally, creating a mobile-optimized model and saving it in PyTorch Lite format.</p><ol><li><strong>Printing the Results (Continuation):</strong></li></ol><pre>print(&quot;----------------------- Model Converted! -----------------------&quot;)<br>print(f&quot;Format: PyTorch Lite, Image Size= {imgsize}&quot;)<br>print(&quot;Model saved!&quot;)<br>print(&quot;&quot;)<br>print(&quot;**********************&quot;)<br>print(&quot;&quot;)</pre><p>Informative messages indicating the successful conversion of the model to PyTorch Lite format.</p><p>all of python code :</p><blockquote>from ultralytics import YOLO<br>import torch<br>import torch.nn as nn<br>import torchvision<br>from time import sleep<br>from torch.utils.mobile_optimizer import optimize_for_mobile</blockquote><blockquote>print(“”)<br>print(“**********************”)<br>print(“”)<br>print(“ — — — — — — — — — — — — Model Converting! — — — — — — — — — — — -”)<br>print(“Please wait, system is running”)<br>print(“”)<br>print(“**********************”)<br>print(“”)</blockquote><blockquote>imgsize = (&lt;img-size&gt;) # Image size must be first height after width!!!</blockquote><blockquote>def xywh2xyxy(x):<br> y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)<br> y[…, 0] = x[…, 0] — x[…, 2] / 2 # top left x<br> y[…, 1] = x[…, 1] — x[…, 3] / 2 # top left y<br> y[…, 2] = x[…, 0] + x[…, 2] / 2 # bottom right x<br> y[…, 3] = x[…, 1] + x[…, 3] / 2 # bottom right y<br> return y</blockquote><blockquote>class WrapperModel(torch.nn.Module):</blockquote><blockquote>def __init__(self, model: torch.nn.Module):<br> super().__init__()<br> self.model = model</blockquote><blockquote>def forward(self, input_tensor: torch.Tensor, conf_thres: float = 0.0):<br> prediction = self.model(input_tensor)<br> bs = prediction.shape[0] <br> nc = (prediction.shape[1] — 4) <br> nm = prediction.shape[1] — nc — 4<br> mi = 4 + nc <br> xc = prediction[:, 4:mi].amax(1) &gt; conf_thres<br> output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs<br> for xi, x in enumerate(prediction): <br> print(f”prediction: {xi}”)<br> x = x.transpose(0, -1)[xc[xi]] <br> print(x.shape)<br> if not x.shape[0]:<br> continue<br> box, cls, mask = x.split((4, nc, nm), 1)<br> box = xywh2xyxy(box)<br> conf, j = cls.max(1, keepdim=True)<br> x = torch.cat((box, conf, j.float(), mask), 1)[conf.view(-1) &gt; conf_thres]<br> n = x.shape[0] <br> if not n: <br> continue<br> x = x[x[:, 4].argsort(descending=True)[:30000]]<br> c = x[:, 5:6] * 0 <br> boxes, scores = x[:, :4] + c, x[:, 4]<br> return x, boxes, scores</blockquote><blockquote>model = YOLO(“&lt;YOLOMODEL-path&gt;”, task=”detect”)<br>model.export(format=”torchscript”, imgsz=imgsize)<br>print(“”)<br>print(“**********************”)<br>print(“”)<br>print(“ — — — — — — — — — — — — Model Converted! — — — — — — — — — — — -”)<br>print(f”Format: torchscript, Image Size= {imgsize}”)<br>print(“Please wait now model converting PyTorch Lite format for Android…”)<br>print(“”)<br>print(“**********************”)<br>print(“”)<br>print(“Please wait….”)<br>print(“”)<br>sleep(3)<br>torchmodel = torch.load(&lt;save-torchscript&gt;) <br>wrapper_model= WrapperModel(torchmodel)<br>scriptedmodel2 = torch.jit.script(wrapper_model)<br>scriptedmodel2.save(&lt;save-torchscript&gt;)<br>“””<br>mobilemodel = optimize_for_mobile(scriptedmodel2) # This option is optional, if you want you can remove this line!<br>mobilemodel._save_for_lite_interpreter(&lt;save-torchscriptlite&gt;)<br>“””<br>print(“”)<br>print(“**********************”)<br>print(“”)<br>print(“ — — — — — — — — — — — — Model Converted! — — — — — — — — — — — -”)<br>print(f”Format: PyTorch Lite, Image Size= {imgsize}”)<br>print(“Model saved!”)<br>print(“”)<br>print(“**********************”)<br>print(“”)</blockquote><h3>CPP USING:</h3><h3>Header and Libraries</h3><pre>#include &lt;iostream&gt;<br>#include &lt;list&gt;<br>#include &lt;string&gt;<br>#include &lt;torch/script.h&gt;<br>#include &lt;torch/types.h&gt;<br>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;opencv2/core/core.hpp&gt;<br>#include &lt;opencv2/imgproc/imgproc.hpp&gt;<br>#include &lt;opencv2/highgui/highgui.hpp&gt;<br>#include &lt;chrono&gt;</pre><p>In this section, necessary C++ libraries, as well as the header files for PyTorch and OpenCV, are included.</p><h3>load_input_image Function</h3><pre>torch::Tensor load_input_image(const std::string&amp; filename, int width, int height) {<br>  cv::Mat image = cv::imread(filename, cv::IMREAD_COLOR);</pre><pre>  if (image.empty()) {<br>    std::cerr &lt;&lt; &quot;Error: &quot; &lt;&lt; filename &lt;&lt; std::endl;<br>    return torch::Tensor();<br>  }</pre><pre>  cv::resize(image, image, cv::Size(width, height));</pre><pre>  torch::Tensor tensor = torch::from_blob(image.data, {image.rows, image.cols, image.channels()}, torch::kByte);</pre><pre>  tensor = tensor.permute({2, 0, 1}).to(torch::kFloat32).div(255.0);</pre><pre>  tensor = tensor.unsqueeze(0);</pre><pre>  return tensor;<br>}</pre><p>This function loads an image from a specified file, resizes it to the specified width and height, converts it to a tensor, and scales pixel values between 0 and 1. The resulting tensor is prepared as input for the model.</p><h3>parse_row Function</h3><pre>std::vector&lt;float&gt; parse_row(torch::Tensor row, int img_width, int img_height) {<br>  float xc = row[0].item&lt;float&gt;();<br>  float yc = row[1].item&lt;float&gt;();<br>  float w = row[2].item&lt;float&gt;();<br>  float h = row[3].item&lt;float&gt;();</pre><pre>  float x1 = (xc - w / 2) / 1920 * img_width;<br>  float y1 = (yc - h / 2) / 1088 * img_height;<br>  float x2 = (xc + w / 2) / 1920 * img_width;<br>  float y2 = (yc + h / 2) / 1088 * img_height;</pre><pre>  int n = row.size(0);</pre><pre>  torch::Tensor probs = row.narrow(0, 4, n - 4);</pre><pre>  auto maxProb = probs.max().item&lt;float&gt;();</pre><pre>  return {x1, y1, x2, y2, maxProb};<br>}</pre><p>This function takes a row from the model’s output tensor and processes it by converting normalized coordinates and adding the probability of the highest probable class. It returns a vector: [x1, y1, x2, y2, maxProb].</p><h3>Box Operations</h3><pre>float intersection(torch::Tensor box1, torch::Tensor box2);<br>float unioner(torch::Tensor box1, torch::Tensor box2);<br>float iou(torch::Tensor box1, torch::Tensor box2);</pre><p>These three functions are used to compute the intersection area, union area, and IoU (Intersection over Union) ratio between two bounding boxes.</p><h3>main Function</h3><pre>int main() {<br>  //...<br>}</pre><p>This function is the main entry point of the program. It coordinates the execution flow of the program.</p><h3>Necessary Variables and Loading Input Image</h3><pre>std::vector&lt;std::string&gt; yolo_classes = {&lt;classes name &quot;&quot;,&quot;&quot;,&quot;&quot;&gt;};</pre><pre>cv::Mat img;<br>img = cv::imread(&lt;image-path&gt;);<br>cv::Size size = img.size();<br>int img_width = size.width;<br>int img_height = size.height;<br>torch::Tensor input = load_input_image(&lt;image-path&gt;, &lt;image-size&gt;);</pre><p>In this part, a vector named yolo_classes is defined to hold the names of the classes. Then, an image is loaded, and its dimensions are obtained. The image is converted to the required format using the load_input_image function.</p><h3>Loading the Model and Running it</h3><pre>torch::jit::script::Module module = torch::jit::load(&lt;torchscript-mode-path&gt;);<br>auto start_time = std::chrono::high_resolution_clock::now();<br>torch::Tensor output = module.forward({input}).toTensor();<br>auto end_time = std::chrono::high_resolution_clock::now();<br>auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(end_time - start_time);<br>std::cout &lt;&lt; &quot;Execution time: &quot; &lt;&lt; duration.count() &lt;&lt; &quot; ms&quot; &lt;&lt; std::endl;<br>output = output[0].transpose(0,1);<br>torch::Tensor row = output[0];</pre><p>The model is loaded using the torch::jit::script::Module class. The prepared input image is passed to the model, and the output is obtained. The execution time of the model is measured and printed. The output tensor is transposed for further processing, and a row from the output is extracted.</p><h3>Processing and Filtering the Output</h3><pre>std::vector&lt;std::vector&lt;float&gt;&gt; filteredRows;<br>for(int i=0; i&lt;output.size(0); i++) {<br>  torch::Tensor row = output[i];<br>  std::vector&lt;float&gt; parsedRow = parse_row(row, img_width, img_height);<br>  if(parsedRow[4] &gt; 0.7) {<br>    filteredRows.push_back(parsedRow);<br>  }<br>}</pre><p>A loop is used to iterate over the output tensor. Each row is processed using the parse_row function, and if the probability of the detected object is greater than a certain threshold (0.7 in this case), the row is added to the filteredRows vector.</p><h3>Visualization and Printing Results</h3><pre>for(auto&amp; row : filteredRows) {<br>  for(int i=0; i&lt;row.size(); i+=5) {<br>    float x1 = row[i];<br>    float y1 = row[i+1]; <br>    float x2 = row[i+2];<br>    float y2 = row[i+3];<br>    //auto  label = std::to_string(row[i+4]);</pre><pre>    cv::rectangle(img, cv::Point(x1,y1), cv::Point(x2,y2),  <br>                  cv::Scalar(0,255,0), 2);</pre><pre>    // cv::putText(img, label, cv::Point(x1,y1), <br>    //           cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0,255,0));<br>  }<br>}</pre><p>Finally, the coordinates of the filtered rows are used to draw rectangles on the original image. The rectangles represent the detected objects. The image is then displayed.</p><p>Make sure to replace placeholders like &lt;classes name &quot;&quot;,&quot;&quot;,&quot;&quot;&gt;, &lt;image-path&gt;, &lt;image-size&gt;, and &lt;torchscript-mode-path&gt; with the actual values for your use case.</p><p>all of cpp code :</p><blockquote>#include &lt;iostream&gt;<br>#include &lt;list&gt;<br>#include &lt;string&gt;<br>#include &lt;torch/script.h&gt;<br>#include &lt;torch/types.h&gt;<br>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;opencv2/core/core.hpp&gt;<br>#include &lt;opencv2/imgproc/imgproc.hpp&gt;<br>#include &lt;opencv2/highgui/highgui.hpp&gt;<br>#include &lt;chrono&gt;<br>torch::Tensor load_input_image(const std::string&amp; filename, int width, int height) {<br> cv::Mat image = cv::imread(filename, cv::IMREAD_COLOR);</blockquote><blockquote>if (image.empty()) {<br> std::cerr &lt;&lt; “Eror: “ &lt;&lt; filename &lt;&lt; std::endl;<br> return torch::Tensor();<br> }</blockquote><blockquote>cv::resize(image, image, cv::Size(width, height));</blockquote><blockquote>torch::Tensor tensor = torch::from_blob(image.data, {image.rows, image.cols, image.channels()}, torch::kByte);</blockquote><blockquote>tensor = tensor.permute({2, 0, 1}).to(torch::kFloat32).div(255.0);</blockquote><blockquote>tensor = tensor.unsqueeze(0);</blockquote><blockquote>return tensor;<br>}</blockquote><blockquote>std::vector&lt;float&gt; parse_row(torch::Tensor row, int img_width, int img_height) {<br> float xc = row[0].item&lt;float&gt;();<br> float yc = row[1].item&lt;float&gt;();<br> float w = row[2].item&lt;float&gt;();<br> float h = row[3].item&lt;float&gt;();</blockquote><blockquote>float x1 = (xc — w / 2) / 1920 * img_width;<br> float y1 = (yc — h / 2) / 1088 * img_height;<br> float x2 = (xc + w / 2) / 1920 * img_width;<br> float y2 = (yc + h / 2) / 1088 * img_height;</blockquote><blockquote>int n = row.size(0);</blockquote><blockquote>torch::Tensor probs = row.narrow(0, 4, n — 4);</blockquote><blockquote>auto maxProb = probs.max().item&lt;float&gt;();</blockquote><blockquote>return {x1, y1, x2, y2, maxProb};<br>}</blockquote><blockquote>float intersection(torch::Tensor box1, torch::Tensor box2) {<br> float box1_x1 = box1[0].item&lt;float&gt;();<br> float box1_y1 = box1[1].item&lt;float&gt;();<br> float box1_x2 = box1[2].item&lt;float&gt;();<br> float box1_y2 = box1[3].item&lt;float&gt;();</blockquote><blockquote>float box2_x1 = box2[0].item&lt;float&gt;();<br> float box2_y1 = box2[1].item&lt;float&gt;();<br> float box2_x2 = box2[2].item&lt;float&gt;();<br> float box2_y2 = box2[3].item&lt;float&gt;();</blockquote><blockquote>float x1 = std::max(box1_x1, box2_x1);<br> float y1 = std::max(box1_y1, box2_y1);<br> float x2 = std::min(box1_x2, box2_x2);<br> float y2 = std::min(box1_y2, box2_y2);</blockquote><blockquote>if (x1 &gt;= x2 || y1 &gt;= y2) {<br> return 0.0f;<br> }</blockquote><blockquote>return (x2 — x1) * (y2 — y1);<br>}</blockquote><blockquote>float unioner(torch::Tensor box1, torch::Tensor box2) {<br> float box1_x1 = box1[0].item&lt;float&gt;();<br> float box1_y1 = box1[1].item&lt;float&gt;();<br> float box1_x2 = box1[2].item&lt;float&gt;();<br> float box1_y2 = box1[3].item&lt;float&gt;();</blockquote><blockquote>float box2_x1 = box2[0].item&lt;float&gt;();<br> float box2_y1 = box2[1].item&lt;float&gt;();<br> float box2_x2 = box2[2].item&lt;float&gt;();<br> float box2_y2 = box2[3].item&lt;float&gt;();</blockquote><blockquote>float box1_area = (box1_x2 — box1_x1) * (box1_y2 — box1_y1);<br> float box2_area = (box2_x2 — box2_x1) * (box2_y2 — box2_y1);</blockquote><blockquote>return box1_area + box2_area — intersection(box1, box2);<br>}</blockquote><blockquote>float iou(torch::Tensor box1, torch::Tensor box2) {<br> return intersection(box1, box2) / unioner(box1, box2);<br>}</blockquote><blockquote>int main() {<br> std::vector&lt;std::string&gt; yolo_classes = {&lt;classes name “”,””,””&gt;};</blockquote><blockquote>cv::Mat img;<br> img = cv::imread(&lt;image-path&gt;);<br> cv::Size size = img.size();<br> int img_width = size.width;<br> int img_height = size.height;<br> <br> torch::Tensor input = load_input_image(&lt;image-path&gt;, &lt;image-size&gt;);<br> <br> torch::jit::script::Module module = torch::jit::load(&lt;torchscript-mode-path&gt;);<br> <br> auto start_time = std::chrono::high_resolution_clock::now();<br> torch::Tensor output = module.forward({input}).toTensor();<br> <br> auto end_time = std::chrono::high_resolution_clock::now();<br> auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(end_time — start_time); <br> std::cout &lt;&lt; “Execution time: “ &lt;&lt; duration.count() &lt;&lt; “ ms” &lt;&lt; std::endl;<br> output = output[0].transpose(0,1);<br> torch::Tensor row = output[0];<br> std::cout &lt;&lt; output.sizes() &lt;&lt; std::endl;</blockquote><blockquote>std::vector&lt;std::vector&lt;float&gt;&gt; filteredRows;<br> <br> for(int i=0; i&lt;output.size(0); i++) {<br> <br> torch::Tensor row = output[i];<br> <br> std::vector&lt;float&gt; parsedRow = parse_row(row, img_width, img_height);<br> <br> if(parsedRow[4] &gt; 0.7) {<br> filteredRows.push_back(parsedRow);<br> }</blockquote><blockquote>}</blockquote><blockquote>std::cout &lt;&lt; filteredRows &lt;&lt; std::endl;<br> for(auto&amp; row : filteredRows) {</blockquote><blockquote>for(int i=0; i&lt;row.size(); i+=5) {</blockquote><blockquote>float x1 = row[i];<br> float y1 = row[i+1]; <br> float x2 = row[i+2];<br> float y2 = row[i+3];<br> //auto label = std::to_string(row[i+4]);</blockquote><blockquote>cv::rectangle(img, cv::Point(x1,y1), cv::Point(x2,y2), <br> cv::Scalar(0,255,0), 2);</blockquote><blockquote>// cv::putText(img, label, cv::Point(x1,y1), <br> // cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0,255,0));</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>cv::imshow(“Image”, img);</blockquote><blockquote>cv::waitKey(0);</blockquote><blockquote>}</blockquote><p>Here, on the cpp outputs, if you cannot find a proper label coordinate on your photo, float intersection(torch::Tensor box1, torch::Tensor box2);<br>float unioner(torch::Tensor box1, torch::Tensor box2);<br>float iou(torch::Tensor box1, torch::Tensor box2); You can change its functions. You can find main.cpp, CMakeLists.txt, convert.py, requirements.txt on my github page along with all the codes. Don’t forget to follow me, I will soon have articles explaining the use of Python with Onnx models, Openvino models.</p><h3>github repo : https://github.com/mock3ng/performanceAI</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d50c35a8b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>