<?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 Slawomir Telega, PhD on Medium]]></title>
        <description><![CDATA[Stories by Slawomir Telega, PhD on Medium]]></description>
        <link>https://medium.com/@telega.slawomir.ai?source=rss-0866c1a979c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6H6WU9tyMG1tFlko</url>
            <title>Stories by Slawomir Telega, PhD on Medium</title>
            <link>https://medium.com/@telega.slawomir.ai?source=rss-0866c1a979c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:21:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@telega.slawomir.ai/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[YOLO v1 implementation: dataset class creation]]></title>
            <link>https://medium.com/@telega.slawomir.ai/yolo-v1-implementation-dataset-class-creation-0822eea4b7fa?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0822eea4b7fa</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[yolov1]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 09:44:26 GMT</pubDate>
            <atom:updated>2025-04-29T09:44:26.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_pqCC03psdbt6Ehvv1HQw.jpeg" /><figcaption><a href="https://unsplash.com/@emmanems19">https://unsplash.com/@emmanems19</a></figcaption></figure><p><em>At a certian point, one gets to a point, where he wants to know algos he’s using at the most basic level. And the only way, I guess, to say that you understand every nut and bolt is to code the algo oneself. Therefore, in my attempt to recreate YOLO v1 from the original paper </em><a href="https://arxiv.org/abs/1506.02640"><em>(https://arxiv.org/abs/1506.02640</em></a><em>), I’ve started with creating a custom dataset. So, here goes…</em></p><p>To create a custom dataset in PyTorch one has to create a class implementingat least <em>__init__</em>, <em>__len__</em> and <em>__getitem__</em>, that inherits from <em>torch.utils.data.Dataset</em> class. The process is described very clearly on <a href="https://pytorch.org/tutorials/beginner/basics/data_tutorial.html">pytorch homepage</a>.</p><p>To make dataset compilant with Yolov1 algo, one has to follow the guidlines outlined in the original paper. I’ve decided to take a standard yolo image dataset, compromising of a directory with images and a separate one with labels (in .txt format).</p><p>Let’s say we have an <em>image_01.jpg</em>. The labels for this file will be stored in <em>image_01.txt</em>, with one line corresponding to one object. The format of line is quite simple — <em>c, x_c, y_c, w, h</em>; here <em>c </em>is the category of the object, <em>(x_c, y_c)</em> are the realative coordinates of the object’s centre with respect to the upper left corner of the image, while <em>(w, h)</em> denoted the relative with and height of the bounding box with respect to the image. Just to give an example, the annotation [2, 0.6, 0.4, 0.25, 0.125] means that an object of category index 2 is located at 0.6 of image’s width and 0.4 of its height, while object’s bounding box width equals 1/4 of images width, and height equals 1/8 of images height.</p><p>On the other hand, YOLO v1 requires a target in a bit different form. As one may now, YOLO algorithm divides (after scalling to 448x448 dim) image into a grid of <em>SxS</em> squares (originally <em>S=7</em>, what gives squares of <em>64x64 </em>size). Therefore, creating dataset consisting of input features and target labels, one should provide input images transformed to <em>448x448xchannels</em> tensor (usually normalized). Target labels should take the form of 3d tensor of dimensions <em>SxSxL</em>, where <em>L=5+number of categories</em>. So, for every grid cell, if there is an object centre inside, we have a vector consisting of five values describing the bounding box (namely <em>1.0, x_c, y_c, w, h</em>) plus one hot encoded vector appended, containing the category of an object. If there is no object centre within the grid cell, we have a vector of same length, filled with zeros. Due to the inner workings of the YOLO algo, <em>x_c</em> and <em>y_c </em>should be relative values, but with respect to the grid cell they are in (position is counted from grid cell’s UL corner), while w and remain as they were, relative to image. Here one may observe a problematic thing in YOLO v1, each grid cell may predict only one class — as there is only one OHE category vector at each grid cell. It may be overcome using finer grid, but generally the first version of YOLO has problems with detection/dicrimination of small objects located next to each other (plus this implementation allows only for one object per grid cell — a simplification justified by the abovementioned “one category per grid cell” boundary condition ;))</p><p>Below I attach the code of the custom dataset class — it is commented, but in case anything seems unclear, do not hesitate to ask :)</p><pre>import torch<br><br>from torch.utils.data import Dataset, DataLoader<br>from torchvision import transforms<br><br>from pathlib import Path<br>from PIL import Image<br><br>class MyImageDataset(Dataset):<br>    <br>    def __init__(self, img_dir:str, lbl_dir:str, <br>                 img_size:tuple=(448, 448), S:int=7, C:int=2):<br><br>        super().__init__()<br>        <br>        self.S = S # grid parameter (cells number = SxS)<br>        self.C = C # number of classes<br>        self.img_size = img_size # image size used by yolo (in v1 (448x448))<br><br>        # define image transforms - values from imageNet<br>        self.img_transforms = transforms.Compose([<br>            transforms.ToTensor(), # float tensor<br>            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), # normalization<br>            transforms.Resize(img_size), # scale to (448, 448)<br>        ])<br><br>        # get label and image files (imgs only if they are annotated)<br>        self.lbl_files, self.img_files = self._get_label_and_image_files(img_dir=img_dir, lbl_dir=lbl_dir)<br>    <br>    def __len__(self):<br><br>        return len(self.lbl_files)<br><br>    def __getitem__(self, idx):<br><br>        # get label and image file paths, corresponding to idx<br>        img_path = self.img_files[idx]<br>        lbl_path = self.lbl_files[idx]<br><br>        # get image and label <br>        image = Image.open(img_path)<br><br>        label_dims = (self.S, self.S, 5 + self.C) # calculate dims of target tensor <br>        label = torch.zeros(size=label_dims, dtype=float) # define target tensor (full of zeros)<br><br>        # read annots from file, and convert it to right format for yolo v1 target<br>        annotations = self._read_annotations_from_txt_file(lbl_path)<br><br>        for annotation in annotations: # loop over annotations<br>            <br>            # get row and col of a responsible grid cell<br>            col = int(annotation[-2]) <br>            row = int(annotation[-1])<br><br>            # insert annots (c, xc, yc, w, h, ohe_vector)  <br>            label[row, col] = torch.Tensor(annotation[:-2])<br><br>        # transform image<br>        image = self.img_transforms(image)<br><br>        return image, label<br>    <br>    def _get_label_and_image_files(self, img_dir:str, lbl_dir:str) -&gt; tuple[list[Path]]:<br>        <br>        img_suffixes: list[str] = [&quot;.jpg&quot;, &quot;.jpeg&quot;, &quot;.gif&quot;, &quot;.png&quot;] # accepted image formats (by torchvision.io.image_decode)<br>        <br>        # get absolute paths to images and labels (in yolo .txt format)<br>        img_path = Path.cwd()/img_dir <br>        lbl_path = Path.cwd()/lbl_dir<br><br>        lbl_files = [lbl for lbl in lbl_path.iterdir() if lbl.is_file()] # label files<br>        lbl_stems = [nm.stem for nm in lbl_files] # filenames without path and extension<br>        img_files = [img for img in img_path.iterdir() if (img.is_file() and img.suffix in img_suffixes and img.stem in lbl_stems)] # image files (only ones with corresponding label .txt file)<br>        return lbl_files, img_files<br><br>    def _read_annotations_from_txt_file(self, filename):<br>        annots: list = []<br>        with open(file=filename, mode=&#39;r&#39;) as fn:<br>            for line in fn:<br>                present_annot = line.strip().split(&#39; &#39;) # get single annotation line into a list of strings <br>                annots.append([float(element) for element in present_annot]) # convert into float and append to annots list (of lists)<br>        <br>        # convert (xc, yc) into absolute (pixels), global values<br>        for annot in annots: <br>            annot[1:3] = self._global_relative_to_absolute(annot[1:3], self.img_size) # convert (xc, yc) into global, absolute values (pixels)<br>            annot[1],annot[2],ind_x,ind_y = self._global_absolute_to_local_relative(annot[1:3], self.img_size, self.S) # convert xc, yc to local, relative values<br>            real_cat = int(annot[0]) # get real object&#39;s category<br>            ohe_vector = self._prepare_class_OHE_vector(real_cat=real_cat, num_classes=self.C) # prepare ohe vector<br>            annot[0] = 1. # required by yolo, means the probability, that an object is detected<br>            annot.extend(ohe_vector) # add ohe vector to the end of annot<br>            annot.extend([ind_x, ind_y]) # append grid cell coords at the end<br>        return annots<br>    <br>    def _global_relative_to_absolute(self, coords: tuple[float], img_size: tuple[int]) -&gt; tuple[float]:<br><br>        return (int(coords[0]*img_size[0]), int(coords[1]*img_size[1]))<br>    <br>    def _global_absolute_to_local_relative(self, coords: tuple[float], img_size: tuple[int], S:int):<br>        # calcualtes the relative postion of (xc, yc) with respect to the grid cell UL corner<br>        <br>        # get grid cell size (in pixels)<br>        dx = img_size[0] // S<br>        dy = img_size[1] // S<br><br>        # get relative xc, yc with respect to grid cell UL corner<br>        rel_x = (coords[0] % dx) / dx <br>        rel_y = (coords[1] % dy) / dy <br><br>        # get grid cell number (index_x, index_y) - each from 0 to S-1<br>        grid_x = (coords[0] // dx) <br>        grid_y = (coords[1] // dy)<br><br>        return rel_x, rel_y, grid_x, grid_y<br>    <br>    def _prepare_class_OHE_vector(self, real_cat:int, num_classes:int) -&gt; list:<br><br>        assert real_cat &lt;= num_classes, &quot;selected category index exceeds number of classes&quot; # make sure, that selected class is within allowed classes<br><br>        # prepare one hot encoded vector<br>        ohe: list = [0.] *num_classes<br>        ohe[real_cat] = 1.<br><br>        return ohe<br></pre><p>The class above may be used to initialze a dataset and create a torch Dataloader from it. Providing the above is in <em>utils.py</em> file and original dataset is in the same directory (namely <em>datset/test/images</em> and <em>dataset/test/labels</em>) we have:</p><pre>import torch<br>from torch.utils.data import DataLoader<br>from utils import MyImageDataset<br><br><br>if __name__ == &quot;__main__&quot;:<br><br>    test_dset = MyImageDataset(img_dir=&quot;dataset/test/images/&quot;, lbl_dir=&quot;dataset/test/labels/&quot;) # create dataset<br>    test_dloader = DataLoader(dataset=test_dset, batch_size=2, shuffle=True) # create dataloader<br>    test_feature, test_label = next(iter(test_dloader)) # check if it works<br></pre><p>And that’s it ;). Current version of the code is available at my GitHub (<a href="https://github.com/SlawekTT/Yolo_v1_dataset">https://github.com/SlawekTT/Yolo_v1_dataset</a>)</p><p>Have a good day and happy coding</p><p>S.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0822eea4b7fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Vision Transformer in PyTorch step by step — Part 3: Positional Encoding]]></title>
            <link>https://medium.com/@telega.slawomir.ai/coding-vision-transformer-in-pytorch-step-by-step-part-3-positional-encoding-6e0d11685e22?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0d11685e22</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[positional-encoding]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[pytorch-tutorial]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 16:56:31 GMT</pubDate>
            <atom:updated>2025-01-16T16:56:31.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coding Vision Transformer in PyTorch step by step — Part 3: Positional Encoding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qsdThb26cc_e2VXel1azw.jpeg" /><figcaption><a href="https://unsplash.com/@henniestander">https://unsplash.com/@henniestander</a></figcaption></figure><p>Broken ankle defintly boosts my productivity ;) . Here we go with the third installment of my ViT in Pytorch series. This time we will delve into the murky world of positional encoding.</p><p>We finished <a href="https://medium.com/@telega.slawomir.ai/coding-vision-transformer-in-pytorch-step-by-step-part-2-patching-images-723d573699d0">last part</a> having our image(s) cut into patches, flattened and projected onto a latent space. Now we have to encode, somehow, position of each of the patches, because the Transformer architecture is invariant with respect to the permutation of the patches. Of course, from our point of view such an invaraince is not existing and the order of patches does matter. So, we have to encode patch position into the patch somehow. Simple indexing is not a good idea, as the number of digits will grow with the number of patches. Same with, say, assigning a float number between 0 and 1, not a practical solution from computational point of view. In the original Transformer paper <a href="https://arxiv.org/abs/1706.03762">Attention is All You Need</a> Vasvani <em>et al</em> proposed encoding method based on trigonometric functions, which will be implemented in this tutorial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*iIcXY0o9jREP9VyzacVdyQ.jpeg" /></figure><p>The above formula allows to generate a vector of <em>d_model</em> length for each of the considered elements (here <em>pos</em> means position in the sequence of elements), while <em>i</em> varies between <em>0</em> and <em>d_model/2</em>. As it may be observed, we obtain <em>d_model/2</em> sines and <em>d_model/2 cosines</em>, for even and odd i values respectively. Therefore, we end up with a vector of length <em>d_model</em> for every element (token in our case) which is unique and therefore might be used for position encoding.</p><p>To make it more clear, I’ll show first a function generating positional encodings with some comments and then we’ll move and code our custom position encoding layer.</p><p>Let’s code:</p><pre>import torch<br>from torch import nn<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Hyperparams<br>D = 512# embedding space dimension<br>N = 10000 # user defined<br>SEQ_LEN = 197 #sequence length <br><br><br>PosEnc = np.zeros((SEQ_LEN, D)) # define encoding matrix of zeros<br><br>for k in range(SEQ_LEN): # loop over all elements<br>    for i in range(D//2): # loop over half of embedding dim<br>        argument = k / (N ** (2 * i/D)) # calculate angle<br>        <br>        ind_e, ind_o = 2 * i, 2 * i + 1 # subsequent even and odd indices<br><br>        PosEnc[k, ind_e] = np.sin(argument) # calculate and insert elements<br>        PosEnc[k, ind_o] = np.cos(argument)</pre><p>It might be illustrative, to plot <em>PosEnc</em> matrix, just to make sure all the rows are unique (plus it looks cool ;) ). Here each row is a vector of length <em>D</em> corresponding to the element described by the y-coordinate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJPyJ4GJ5Cc505Fcp8csnw.jpeg" /></figure><p>To encode positions in our sequence, we simply rows of the above matrix to respective token (obtained previously from patches).</p><p>Now, we may code the above algorithm in a form of a torch layer, subclassing <em>nn.Module</em>.</p><pre>class MyViT_PosEncode(nn.Module):<br>    <br>    def __init__(self, seq_len:int=197, pos_enc_dim:int=512)-&gt;None:<br>        super().__init__()<br>        pos_enc = torch.zeros(seq_len, pos_enc_dim) # initialize tensor<br>        <br>        for k in range(seq_len): # loop over tokens<br>            for i in range(pos_enc_dim//2): # loop over encoding dim<br>                # calculate angle<br>                argument : float = torch.tensor(k / (10000 ** (2 * i/pos_enc_dim)))<br>                # calculate subsequent indices<br>                ind_e, ind_o = 2 * i, 2 * i + 1<br>                # calculate and input values<br>                pos_enc[k, ind_e] = torch.sin(argument)<br>                pos_enc[k, ind_o] = torch.cos(argument)<br>        <br>        # explaind later on<br>        self.register_buffer(&#39;pos_enc&#39;, pos_enc)<br>    <br>    def forward(self, x):<br>        return x + self.pos_enc # add encodings to x</pre><p>The only new thing here is the use of <em>.register_buffer</em> method. It allows pytorch to track and save (if needed) <em>pos_enc</em>, but makes it unchangeable (can’t be updated).</p><p>And that’s it for now. We got a working custom Torch layer performing positional encoding on an input tensor.</p><p>Till the next time</p><p>Happy Coding</p><h3>References:</h3><ol><li><strong>Attention is All You Need</strong>, A. Vasvani et al, <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a></li><li><strong>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</strong>, A. Dosovitskiy et al, <a href="https://arxiv.org/abs/2010.11929">arXiv:2010.11929</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0d11685e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Vision Transformer in PyTorch step by step — Part 2: Patching Images]]></title>
            <link>https://medium.com/@telega.slawomir.ai/coding-vision-transformer-in-pytorch-step-by-step-part-2-patching-images-723d573699d0?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/723d573699d0</guid>
            <category><![CDATA[unfold]]></category>
            <category><![CDATA[patching]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 11:28:48 GMT</pubDate>
            <atom:updated>2025-01-16T16:57:45.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coding Vision Transformer in PyTorch step by step — Part 2: Patching Images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLkPwOR4MgbchTJUOGOFeQ.jpeg" /><figcaption><a href="https://unsplash.com/@jaysung">https://unsplash.com/@jaysung</a></figcaption></figure><p>Welcome to the second part of the tutorial. Today we’re going to start working on actual ViT and go from images, via patching, linear mapping and concatenation, to tokens.</p><p>In the original ViT paper, <strong>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</strong>, Dosovitskiy <em>et al</em> proposed the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SoXHGxDPUqFQHFbJKYoVLg.png" /></figure><p>In this tutorial we will code first part of the above diagram, namely, we will go from images to patches, which will in turn be transformed into a latent space using linear projection and a extra token (learnable, responsible for classification) will be added. Finishing, we will have a layer (subclass of nn.Module) which performs all the abovementioned.</p><p>First thing to do is to cut image into non-overlapping patches of a predefined size. Of course, as image is a tensor now (see <a href="https://medium.com/@telega.slawomir.ai/coding-visual-transformer-in-pytorch-step-by-step-part-1-datasets-generation-0c2600cf28a4">previous tut</a> ), we could go the easy way using slices, but it is soooo slow… Therefore we will use <em>Unfold</em> method from <em>torch.nn</em>, which, while being at first a bit non-intuitional, is really fast. Below I show a piece of code, demonstrating how it works:</p><pre># We have an image (img) taken from the dataloader in the format (C, H, W)<br>P = 16 # patch size<br>C, H, W = img.shape # get dims of the image<br>print(img.shape)# torch.Size([3, 224, 224])<br><br>patcher = torch.nn.Unfold(kernel_size=P, stride=P) # define Unfold params<br>patches = patcher(img) # get the patches<br>print(patches.shape) # torch.Size([768, 196])<br><br># So now the image has been cut into 196 patches of 768 points each. <br># The size of the patch equals to CxPxP. Just for the sake of illustration <br># we may come back to image-like format (i.e. (num_patches, P, P, C)), <br># which may be plotted if somebody would like to do so<br><br>patches = patches.view(C, P, P, -1).permute(3, 1, 2, 0)<br><br># after reorganizing dimensions, we permute the channels <br># (so as color C is the last, while number of patches is the first)<br><br>print(patches.shape) # torch.Size([196, 16, 16, 3])<br><br>#Now, as mentioned, each patch can plotted, as a normal image </pre><p>As you see, the whole trick is in choosing the patch sized <em>PxP</em> with stride equal to<em> (P, P)</em> what means we do not have any overlap.</p><p>The knowledge we now posses is more than enough to create our own torch ViT patching layer. Only two more things to consider:</p><ol><li>After obtaining the patches it is usual to pass them through a learnable linear layer that takes in a patch of size CxPxP and outputs a vector of length equal to our chosen latent_dim;</li><li>We add an extra token, full of zeros, at the beginning of our tokenized image, using concatenation. This extra token will be used to store predictions about the class.</li></ol><pre>class VIT_Patch_Layer(nn.Module): # subclass nn.Module<br>    <br>    def __init__(self, patch_dim=16, token_size=100):<br>        super().__init__() # run parent&#39;s init<br>        <br>        self.patch_dim = patch_dim # dimension of a patch<br>        self.latent_dim = latent_dim# latent dimension<br>        <br>        # prepare unfolding <br>        self.unfold = nn.Unfold(kernel_size=patch_dim, stride=patch_dim)<br>        <br>        <br>    def forward(self, x):<br>        <br>        batch_size, c, h, w = x.shape # get dimensions from a batch <br>        patch_size = c * self.patch_dim * self.patch_dim # patch size<br>        <br>        # create extra token of the same lenght as other tokens (token_size)<br>        extra_token = torch.zeros(batch_size, 1, self.latent_dim)<br>        <br>        # batch_size x num_patches x patch_size<br>        x = self.unfold(x).permute(0, 2, 1) <br>        <br>        # pass through linear layer<br>        x = nn.Linear(patch_size, self.latent_dim)(x)<br>        <br>        # add extra token as the first token<br>        x = torch.cat((extra_token, x), dim=1)<br>        <br>        return x</pre><p>To check we may pass a single image (<em>CxHxW</em>) throught the layer:</p><pre>print(img.shape) # torch.Size([3, 224, 224])<br>img = img.unsqueeze(0) # add batch dimension<br>print(img.shape) # torch.Size([1, 3, 224, 224])<br><br>patcher_layer = VIT_Patch_Layer() # make layer instance with default params<br>patched_img = patcher_layer(img) # pass image<br>print(patched_img.shape) # torch.Size([1, 197, 100]) </pre><p>We can make sure that the number are right, by calculating the number of patches we should get and comparing with the output:</p><pre>image_size = 3 x 224 x 224 = 150 528<br>patch_size = 16 x 16 x 3 = 768<br><br>number of tokens = image_size / patch_size = 196 <br><br>But we have one extra token, so:<br><br>total number of tokens = number of tokens + 1 = 197</pre><p>So, the numbers are right and we’ve managed to reduce a bit future computational effeort by latent dim projection. And that’s it for today. Next time we’ll try and add positional encoding into our code.</p><p>Till then</p><p>Happy Coding</p><h3>References:</h3><ol><li><strong>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</strong>, A. Dosovitskiy et al, <a href="https://arxiv.org/abs/2010.11929">arXiv:2010.11929</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=723d573699d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Visual Transformer in PyTorch step by step — Part 1: datasets generation]]></title>
            <link>https://medium.com/@telega.slawomir.ai/coding-visual-transformer-in-pytorch-step-by-step-part-1-datasets-generation-0c2600cf28a4?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c2600cf28a4</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[visual-transformer]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[vit]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 11:16:35 GMT</pubDate>
            <atom:updated>2025-01-16T11:30:19.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coding Vision Transformer in PyTorch step by step — Part 1: Datasets Generation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*096rCNRbryKloqeEy76o9Q.jpeg" /><figcaption><a href="https://unsplash.com/@contrastband">https://unsplash.com/@contrastband</a></figcaption></figure><p>I’ve decided to switch from TensorFlow/Keras and learn PyTorch. And the best way of learning (for me) is to recode scientific papers in my own way. As most of my professional work is connected with Computer Vision and Object Detection, it seemed natural to do something in the very field. Therefore, I’ve chosen to recreate vanilla ViT, in a simplified/custom way.</p><p>First thing to do is generating <em>Train</em> and <em>Test </em><strong><em>Datasets</em></strong> and subsequently respective <strong><em>Dataloaders</em></strong>. It can be done the longer way, by subclassing the generic PyTorch’s <em>Dataset</em> class, or using a ready <em>ImageFolder</em> class (from <em>torchvision</em>), which is faster and suits my needs. I’ve decided to go the latter way.</p><p>ImageFolder allows to create dataset from a directory structure, automatically labeling images. You can,optionally, also transform images and labels on the fly. On the input we have to provide a directory structure of images, of the following kind:</p><pre>data<br>    train<br>      category_a<br>        img_a_1.jpg<br>        img_a_2.jpg<br>        img_a_3.jpg<br>        .<br>        .<br>        .<br>      category_b<br>        img_b_1.jpg<br>        img_b_2.jpg<br>        img_b_3.jpg<br>        .<br>        .<br>        .<br>      category_c<br>    test<br>      category_a<br>      category_b<br>      category_c</pre><p>So we have a root directory, with two subdirs <em>train</em> and <em>test</em> (a third one, <em>valid</em>, of course can be added). In each there are subdirs named after a category which images inside it belong to.</p><p>Before genearating datasets we have to consider what transforms we would like to perform on the images during the process. Of course it could be done later on, but it is really easy to do it while using <em>ImageFolder</em>. One simply has to import <em>transforms </em>from <em>torchvision</em>, and compose a collection of transforms to be applied to each of the images:</p><pre>from torchvision import transforms<br><br>custom_transforms = transforms.Compose([transforms.Resize((224, 224)),<br>                                        transforms.ToTensor()])</pre><p>In the above I created a composition of two transforms: <em>Resize </em>and <em>ToTensor</em>, which resize each image to (224, 224) dimensions (height x width, channels unchanged) and then converts it from image to tensor, scaled to <strong>float</strong> (0., 1.) range (there exists also <em>PILToTensor</em> transform, which outputs a tensor with <strong>uint8</strong> (0, 255) range)</p><p>So now we have everything we need to generate datasets. It is quite straightforward:</p><pre>from torch.utils.data import Dataset, DataLoader<br>from torchvision.datasets import ImageFolder<br><br>train_dataset = ImageFolder(root=&#39;data/train&#39;,<br>                            transform=custom_transforms, <br>                            target_transform=None)<br>test_dataset = ImageFolder(root=&#39;data/test&#39;, <br>                           transform=custom_transforms,<br>                           target_transform=None)</pre><p>As an output we get datasets, labelled after subcategories’ names. We may obtain the classes/categories names reading .<em>classes</em> parameter of the dataset or, if one prefers a dictionary there is a method called <em>class_to_idx()</em>.</p><p>Only thing that remains is to generate<em> Dataloaders, </em>which is as simple as it can be:</p><pre>train_dataloader = DataLoader(train_dataset, <br>                              batch_size=32, <br>                              shuffle=True)<br><br>test_dataloader = DataLoader(test_dataset, <br>                             batch_size=32,<br>                             shuffle=False)</pre><p>Here <em>batch_size </em>variable stands for a number of images in a single batch and <em>shuffle </em>boolean decides if the dataset will be shuffled before batching or not.</p><p>If, for some reason, one is interested in inspecting images and labels in batches, it may be done by iterating over the dataloader, and then accesing the image/label pair we are interested in by indexing:</p><pre>class_names = test_dataset.classes # get categories&#39; names<br><br>features, labels = next(iter(test_dataloader)) # get next batch<br><br>label = labels[0].item() # first label (number)<br>img = features[0] # image, in format [ColorChannels, Height, Width]<br>img = img.permute(1, 2, 0) # change order to [H, W, C] for plotting<br><br>label_name = class_names[label] # get category/class name</pre><p>And that’s it. For the sake of completeness I attach the whole code below.</p><p>Happy coding</p><p>Cheers</p><pre>import torch<br>from torchvision import transforms<br>from torch.utils.data import Dataset, DataLoader<br>from torchvision.datasets import ImageFolder<br><br>custom_transforms = transforms.Compose([transforms.Resize((224, 224)),<br>                                        transforms.ToTensor()])<br><br><br>train_dataset = ImageFolder(root=&#39;data/train&#39;,<br>                            transform=custom_transforms, <br>                            target_transform=None)<br><br>test_dataset = ImageFolder(root=&#39;data/test&#39;, <br>                           transform=custom_transforms,<br>                           target_transform=None)<br><br>train_dataloader = DataLoader(train_dataset, <br>                              batch_size=32, <br>                              shuffle=True)<br><br>test_dataloader = DataLoader(test_dataset, <br>                             batch_size=32,<br>                             shuffle=False)<br><br>class_names = test_dataset.classes # get categories&#39; names<br><br>features, labels = next(iter(test_dataloader)) # get next batch<br><br>label = labels[0].item() # first label (number)<br>img = features[0] # image, in format [ColorChannels, Height, Width]<br>img = img.permute(1, 2, 0) # change order to [H, W, C] for plotting<br><br>label_name = class_names[label] # get category/class name</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c2600cf28a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Base64 coding from the scratch]]></title>
            <link>https://medium.com/@telega.slawomir.ai/base64-coding-from-the-scratch-3237f74e7c6f?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3237f74e7c6f</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[base64-encode]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[base64]]></category>
            <category><![CDATA[base64string]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 14:16:16 GMT</pubDate>
            <atom:updated>2025-01-07T14:16:16.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_-t-gXah_6fQVT7r2kAZA.jpeg" /><figcaption><a href="https://unsplash.com/@comparefibre">https://unsplash.com/@comparefibre</a></figcaption></figure><p>It came to me, that it might be both interesting and educative, to actually write a piece of code, that encodes data using the famous Base64 coding. Therefore, here we go…</p><p>To encode an ASCII string using Base64, one has to perform few steps:</p><p>Generate Base64 character table — encoding uses a reduced ASCII range, namely [A, B, C, …X, Y, Z, a, b, c, …x, y, z, 0, 1, 2, …7, 8, 9,+, /]</p><pre>import numpy as np<br><br>input_text : str = &quot;Number_42_&quot;<br><br>base64_alphabet_string :str = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;<br>base64_alphabet_string += &quot;abcdefghijklmnopqrstuvwxyz&quot;<br>base64_alphabet_string += &quot;0123456789+/&quot;<br><br>def _generate_base64_dict(alphabet:str) -&gt; dict:<br>    base64_dict = {}<br>    for i, letter in enumerate(alphabet):<br>        base64_dict[i] = letter  <br>    return base64_dict<br><br>b64_dict = _generate_base64_dict(alphabet=base64_alphabet_string)</pre><p>We get:</p><pre>{0: &#39;A&#39;, 1: &#39;B&#39;, 2: &#39;C&#39;, 3: &#39;D&#39;, 4: &#39;E&#39;, 5: &#39;F&#39;, 6: &#39;G&#39;, 7: &#39;H&#39;, 8: &#39;I&#39;,<br> 9: &#39;J&#39;, 10: &#39;K&#39;, 11: &#39;L&#39;, 12: &#39;M&#39;, 13: &#39;N&#39;, 14: &#39;O&#39;, 15: &#39;P&#39;, 16: &#39;Q&#39;,<br> 17: &#39;R&#39;, 18: &#39;S&#39;, 19: &#39;T&#39;, 20: &#39;U&#39;, 21: &#39;V&#39;, 22: &#39;W&#39;, 23: &#39;X&#39;, 24: &#39;Y&#39;,<br> 25: &#39;Z&#39;, 26: &#39;a&#39;, 27: &#39;b&#39;, 28: &#39;c&#39;, 29: &#39;d&#39;, 30: &#39;e&#39;, 31: &#39;f&#39;, 32: &#39;g&#39;,<br> 33: &#39;h&#39;, 34: &#39;i&#39;, 35: &#39;j&#39;, 36: &#39;k&#39;, 37: &#39;l&#39;, 38: &#39;m&#39;, 39: &#39;n&#39;, 40: &#39;o&#39;,<br> 41: &#39;p&#39;, 42: &#39;q&#39;, 43: &#39;r&#39;, 44: &#39;s&#39;, 45: &#39;t&#39;, 46: &#39;u&#39;, 47: &#39;v&#39;, 48: &#39;w&#39;,<br> 49: &#39;x&#39;, 50: &#39;y&#39;, 51: &#39;z&#39;, 52: &#39;0&#39;, 53: &#39;1&#39;, 54: &#39;2&#39;, 55: &#39;3&#39;, 56: &#39;4&#39;,<br> 57: &#39;5&#39;, 58: &#39;6&#39;, 59: &#39;7&#39;, 60: &#39;8&#39;, 61: &#39;9&#39;, 62: &#39;+&#39;, 63: &#39;/&#39;}</pre><p>Convert input string into decimal ASCII values</p><pre>def _str_to_ascii(text:str) -&gt; list[int]:<br>    return [ord(letter) for letter in text]<br><br>ascii_dec = _str_to_ascii(text=input_text)</pre><p>We get:</p><pre>[78, 117, 109, 98, 101, 114, 95, 52, 50, 95]</pre><p>Convert ASCII values into binary (base 2) system</p><pre>def _ascii_int_to_bin(ascii_int:list[int]) -&gt; list[str]:<br>    return [format(int_val, &#39;08b&#39;) for int_val in ascii_int]<br><br>ascii_bin = _ascii_int_to_bin(ascii_int=ascii_dec)</pre><p>We get:</p><pre>[&#39;01001110&#39;, &#39;01110101&#39;, &#39;01101101&#39;, &#39;01100010&#39;, &#39;01100101&#39;,<br> &#39;01110010&#39;, &#39;01011111&#39;, &#39;00110100&#39;, &#39;00110010&#39;, &#39;01011111&#39;]</pre><p>Concatenate all and slice into 6-bit chunks</p><pre>def _six_bit_chunks(ascii_bin:list[str]) -&gt; list[str]:<br><br>    joined_string : str = &quot;&quot;.join(ascii_bin)<br>        <br>    division_reminder : int = len(joined_string) % 6<br>        <br>    if division_reminder != 0:<br>        added_zeros = (6-division_reminder)*&quot;0&quot;<br>        joined_string += added_zeros<br>        <br>    division_result : int = len(joined_string) // 6<br>        <br>    chunks_list = [joined_string[6*i : 6*(i+1)] for i in range(division_result)]<br><br>    return chunks_list<br><br>six_chunks = _six_bit_chunks(ascii_bin)</pre><p>We get:</p><pre>[&#39;010011&#39;, &#39;100111&#39;, &#39;010101&#39;, &#39;101101&#39;, &#39;011000&#39;, &#39;100110&#39;,<br> &#39;010101&#39;, &#39;110010&#39;, &#39;010111&#39;, &#39;110011&#39;, &#39;010000&#39;, &#39;110010&#39;,<br> &#39;010111&#39;, &#39;110000&#39;]</pre><p>Return to decimal — in other words, generate indices to be searched in previously prepared (in Point 1) Base64 character table</p><pre>def _bin_to_decimal(chunks:list[str]) -&gt; list[int]:<br>    return [int(chunk, 2) for chunk in chunks]<br><br>b64_indices = _bin_to_decimal(six_chunks)</pre><p>We get:</p><pre>[19, 39, 21, 45, 24, 38, 21, 50, 23, 51, 16, 50, 23, 48]</pre><p>Encode message using Base64 character table</p><pre>def _decimal_to_base64(b64_indices:list[int], b64_dict:dict) -&gt; str:<br>    b64_string : str = &quot;&quot;<br>    for ind in b64_indices:<br>        b64_string += b64_dict[ind]<br>    <br>    # to decode, the number of characters should be divisible by 4,<br>    # beacuse each initial 3 characters are converted into 4 base64 characters<br>    # therefore, if needed we have to add a number of &quot;=&quot; signs at the end<br>    <br>    division_reminder : int = len(b64_string) % 4<br>    if division_reminder != 0:<br>        added_signs = (4-division_reminder) * &quot;=&quot;<br>        b64_string += added_signs<br>    return b64_string<br><br>encoded_text = _decimal_to_base64(b64_indices, b64_dict)</pre><p>We get:</p><pre>TnVtYmVyXzQyXw==</pre><p>One interesting thing to notice, are two “=” signs added at the end — as each three characters in original text are converted into four characters, it may happen that initial string may not be divisible by three and we will get am output not divisible by four, which can be problematic. Therefore, in such case, we add needed number of “=” signs (which are outside Base64 character table) to make length divisible by four.</p><p>And that’s it. For the sake of clarity, I attach the whole code below.</p><pre>import numpy as np<br><br>input_text : str = &quot;Number_42_&quot;<br><br>base64_alphabet_string :str = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;<br>base64_alphabet_string += &quot;abcdefghijklmnopqrstuvwxyz&quot;<br>base64_alphabet_string += &quot;0123456789+/&quot;<br><br>def _generate_base64_dict(alphabet:str) -&gt; dict:<br>    base64_dict = {}<br>    for i, letter in enumerate(alphabet):<br>        base64_dict[i] = letter  <br>    return base64_dict<br><br>def _str_to_ascii(text:str) -&gt; list[int]:<br>    return [ord(letter) for letter in text]<br><br>def _ascii_int_to_bin(ascii_int:list[int]) -&gt; list[str]:<br>    return [format(int_val, &#39;08b&#39;) for int_val in ascii_int]<br><br>def _six_bit_chunks(ascii_bin:list[str]) -&gt; list[str]:<br><br>    joined_string : str = &quot;&quot;.join(ascii_bin)<br>        <br>    division_reminder : int = len(joined_string) % 6<br>        <br>    if division_reminder != 0:<br>        added_zeros = (6-division_reminder)*&quot;0&quot;<br>        joined_string += added_zeros<br>        <br>    division_result : int = len(joined_string) // 6<br>        <br>    chunks_list = [joined_string[6*i : 6*(i+1)] for i in range(division_result)]<br><br>    return chunks_list<br><br>def _bin_to_decimal(chunks:list[str]) -&gt; list[int]:<br>    return [int(chunk, 2) for chunk in chunks]<br><br>def _decimal_to_base64(b64_indices:list[int], b64_dict:dict) -&gt; str:<br>    b64_string : str = &quot;&quot;<br>    for ind in b64_indices:<br>        b64_string += b64_dict[ind]<br>    <br>    # to decode, the number of characters should be divisible by 4,<br>    # beacuse each initial 3 characters are converted into 4 base64 characters<br>    # therefore, if needed we have to add a number of &quot;=&quot; signs at the end<br>    <br>    division_reminder : int = len(b64_string) % 4<br>    if division_reminder != 0:<br>        added_signs = (4-division_reminder) * &quot;=&quot;<br>        b64_string += added_signs<br>    return b64_string<br><br>b64_dict = _generate_base64_dict(alphabet=base64_alphabet_string)<br>ascii_dec = _str_to_ascii(text=input_text)<br>ascii_bin = _ascii_int_to_bin(ascii_int=ascii_dec)<br>six_chunks = _six_bit_chunks(ascii_bin)<br>b64_indices = _bin_to_decimal(six_chunks)<br>encoded_text = _decimal_to_base64(b64_indices, b64_dict)</pre><p>Have fun and happy coding</p><p>Cheers</p><p>S.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3237f74e7c6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coin toss simulation in python — a numerical experiment]]></title>
            <link>https://medium.com/@telega.slawomir.ai/coin-toss-simulation-in-python-a-numerical-experiment-8073e9a3aefb?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8073e9a3aefb</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 09:07:24 GMT</pubDate>
            <atom:updated>2025-01-06T09:07:24.313Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coin toss simulation in python — a numerical experiment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-fbOmcQNj5BTEy6uJotng.jpeg" /><figcaption><a href="https://unsplash.com/@varrak">https://unsplash.com/@varrak</a></figcaption></figure><p>The subject of this tutorial is quite afar from my professional interests, but I have to admit, statistical simulations always fascinated me. So, sitting at home with a broken ankle, I’ve decided, to give it a try and write something simple, yet still being a “<em>numerical experiment</em>”</p><p>The idea is simple, I want to play a simple game of three coin tossing. If all the outcomes of tosses will be the same (i.e. three “heads” or three “tails”) — I win. In other case, I lose. The aim of the experiment is to estimate my winning probability.</p><p>Probably the simplest way to model such an event is to use <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html"><em>choice()</em></a> method from <em>numpy.random</em>, which generates a random sample from a given distribution. Below I present a simple function simulating the tosses:</p><pre>def three_coins_toss(s_space:list[str], probs:list[float]) -&gt; list[str]:<br>    return np.random.choice(a=s_space, p=probs, size=3, replace=True)</pre><p>As it can be seen, I need sample space (i.e. the set of all the possible outcomes of a one-coin toss) and corresponding probabilities. <em>Size</em> is the number of tosses (in this case equal to 3, as this is the number of coins tossed), while <em>replace=True</em>, means we <em>return</em> outcome, after each toss, back to the <em>sample space</em>, so it may appear again (i.e. after getting “heads” in the first try, we may again get it in the second or the third). Outcome of the function will be a list of size 3, containing the results of three tosses (e.g. [“head”, “tail”, “head”])</p><pre>sample_space : list[str] = [&quot;head&quot;, &quot;tail&quot;]<br>probabilities : list[float] = [0.5, 0.5]</pre><p>Next, I need a function to check, if I won(i.e. got three “heads” or three “tails”). One of the possibilities is to make a <strong>set </strong>out of <em>three_coin_toss()</em> result (which is a list) and check its length. As the <strong>set</strong> will remove any redundancies (repeating elements) from the <strong>list </strong>(e.g <em>[a, a, a, b, b] </em>will be transformed to <em>[a,b]</em>), the winning condition will reduce to checking if set’s length equals 1 (as <em>set([“tails”, “tails”, “tails”]) = [“tails]</em>).</p><pre>def check_success(result:list[str]):<br>    return len(set(result))==1</pre><p>So now I am able to simulate a single tossing of three coins. To learn something about the winning probability I have to repeat the process many times and then try to draw some conclusions. Of course, the problem is trivial and can be solved on a piece of paper without much fuss:</p><pre>sample space = {[H, H, H], [H, H, T], [H, T, H], [T, H, H], [H, T, T], <br>                [T, H, T], [T, T, H], [T, T, T]}<br>winning results = {[H, H, H], [T, T, T]}<br><br>winning probability = 2/8 = 0.25</pre><p>but it is interesting to see, if I can get something similar from the simulated experiment. So the idea is to set the number of three coin tosses and see how many times I win (or more precisely, the winning frequency which is a measure of probability):</p><pre>number_of_tosses : int = 512<br><br>probabillity_of_success = <br>  np.mean([check_success(<br>    result=three_coins_toss(s_space=sample_space,probs=probabilities)) <br>    for _ in range(number_of_tosses)])</pre><p>In the above I simply use the implicit for loop to generate a list of results (<strong>True</strong> for wins and <strong>False</strong> for losses), and then take an average of it (in this event the list of bools implicitly gets converted to <strong>1</strong>s and <strong>0</strong>s). The result is the frequency of winning, which is the seek probability</p><p>So, for 512 three-coin tosses (setting <em>random seed</em> to 42, as it is <a href="https://simple.wikipedia.org/wiki/42_(answer)"><strong><em>the Answer to the Ultimate Question of Life, the Universe, and Everything</em></strong></a>), I get the result <strong>P = 0.248</strong>, which actually is quite close to the exact value of <strong>0.250</strong>. Just for fun, I may check, how the result approaches the true value of 0.25 for the increasing number of tosses:</p><pre>number_of_tosses : int = 1<br>for i in range(16):<br>    <br>    probabillity_of_success = np.mean([check_success(result=three_coins_toss(s_space=sample_space,probs=probabilities)) <br>               for _ in range(number_of_tosses)])<br>    print(number_of_tosses, probabillity_of_success)<br>    number_of_tosses *= 2</pre><p>and get the following for the first few powers of 2:</p><pre>1 0.0<br>2 0.0<br>4 0.0<br>8 0.375<br>16 0.125<br>32 0.15625<br>64 0.296875<br>128 0.328125<br>256 0.2109375<br>512 0.248046875<br>1024 0.2412109375<br>2048 0.24365234375<br>4096 0.254638671875<br>8192 0.24853515625<br>16384 0.2513427734375<br>32768 0.250732421875​</pre><p>It may be observed, that starting from the 10th power of 2 I start getting reasonable results, with a relative error less than 2%, which is quite satisfying.</p><p>I attach the whole code, for the sake of experiments. If you find it interesting, or even, hopefully, entertaining, please leave a comment.</p><p>Happy coding</p><p>Cheers</p><pre>import numpy as np<br><br>np.random.seed(42)<br><br>def three_coins_toss(s_space:list[str], probs:list[float]) -&gt; list[str]:<br>    return np.random.choice(a=s_space, p=probs, size=3, replace=True)<br><br>def check_success(result:list[str]):<br>    return len(set(result))==1<br><br>sample_space : list[str] = [&quot;head&quot;, &quot;tail&quot;]<br>probabilities : list[float] = [0.5, 0.5]<br><br>number_of_tosses : int = 1<br><br>for i in range(16):<br>    <br>    probabillity_of_success = np.mean([check_success(result=three_coins_toss(s_space=sample_space,probs=probabilities)) <br>               for _ in range(number_of_tosses)])<br>    print(number_of_tosses, probabillity_of_success)<br>    number_of_tosses *= 2</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8073e9a3aefb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple YOLO custom dataset automatic generation]]></title>
            <link>https://medium.com/@telega.slawomir.ai/simple-yolo-custom-dataset-automatic-generation-295f5c9ccfb2?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/295f5c9ccfb2</guid>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 11:12:31 GMT</pubDate>
            <atom:updated>2024-08-16T11:12:31.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>YOLO custom dataset automatic generation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrAvBcJTkXsCLnUiIKsi2w.jpeg" /><figcaption><a href="https://unsplash.com/@rocknrollmonkey">https://unsplash.com/@rocknrollmonkey</a></figcaption></figure><h3>Introduction</h3><p>Preparation of a custom dataset for YOLO (or any other Object Detection) is a long and not extremaly exciting process. In some cases, it is possible to use a simple idea and make it almost automatic.</p><p>The idea is really, really simple — based on Venn Diagrams (high school math ;)). To give an example, let’s suppose we have to create a custom dataset that will be used to detect, say, soccer players . So, observing that the set consisiting of soccer players is a subset of the set containing all the people, actually defines a simple way to get the bounding boxes / segmentation masks.</p><p>The flow diagram is as follows:</p><ol><li>Get images of people playing soccer and people in general</li><li>Run YOLO detection on the above sets using standart COCO-trained weights and extract results you’re interested in</li><li>Generate directory structure, images’ descriptions and YAML file — so as to obtain a custom dataset</li><li>Train with YOLO to get new weights</li><li>Enjoy ;)</li></ol><p>So, let’s get coding !</p><h3>1. Gather images</h3><p>Manual gathering of images is something we usually would like to avoid, especially if creating a script to automate the task is simple and quick. If one is in possesion of video clips of a soccer match and video clips of people not playing soccer, it is quite straightforward to extract frames from the above movies and store them in separate directories. The simple extraction code is presented below. The only interesting thing is “start_index” variable — if you have, say, 2 videos, then running the code on the first one you set “start_index” to 0, which causes the saved files to be named “img_0.jpg”, “img_1.jpg”, … and so on, up to the last frame grabbed — e.g. “img_100.jpg”. So, processing the second video you should set “start_index” equal to the numer of images grabbed from the previuos movie (in this case 100) plus 1 — therefore, for the second movie in our case “start_index=101”. The variable “frame_skip” means that we grab a frame every “frame_skip” frames — setting it to FPS value will get you a frame every second.</p><pre>import cv2<br>import os<br><br>def grabFramesFromMP4(filename, frame_skip=100):<br>    cap = cv2.VideoCapture(filename=filename)<br>    start_index=101<br>    img_counter=0<br><br>    while True:<br>        ret, frame = cap.read()<br>        assert ret<br><br>        if counter%frame_skip == 0:<br>            file = os.getcwd() + &quot;/images/img_&quot;+str(img_counter+start_index)+&quot;.jpg&quot;<br>            cv2.imwrite(file, frame)<br>            img_counter += 1   <br>    cap.release()<br><br><br>if __name__ = &quot;__main__&quot;:<br>  grabFramesFromMP4(filename=&quot;video_file.mp4&quot;, frame_skip=30)</pre><h3>2. YOLO detection using COCO</h3><p>Next step consists of running the YOLO detection with standard set of weights (I strongly suggest using ‘yolov8x.pt’ for better output), getting info from results for each image (only for the classes we’re interested in — in this case it is class “0” — people) and storing it. As this section and the next one (3. Custom set preparation) are logically connected, the code for both is below the subsequent.</p><h3>3. Custom set preparation</h3><p>Now we have to generate the directory structure requested by YOLO during training phase, fill with images accompanied by (extracted previously) annotations (assigning our own classes — let’s say ordinary people will still be 0, while soccer players will constitute class number 1) — at the same time randomly (but keeping the assumed proportion) assigning to train and validation datasets and finally generate a YAML script to be used by YOLO during training. Code below:</p><pre><br>from ultralytics import YOLO<br>import cv2<br>import os<br>import shutil<br>import random<br><br><br><br>class CustomDataset():<br><br>    def __init__(self, yolo_weights=&quot;yolov8x.pt&quot;, <br>                 categories=[&quot;ordinary people&quot;, &quot;soccer players&quot;], output_dir=&quot;dataset&quot;, <br>                 custom_dir=&quot;custom_dataset&quot;, train_val_split_ratio=0.9) -&gt; None:<br>        self.yolo_model = YOLO(yolo_weights)<br>        self.categories = categories # categories of images<br>        self.output_dir = output_dir # parent directory for images<br>        self.custom_dir = custom_dir # directory for yolo dataset<br>        self.train_val_split_ratio = train_val_split_ratio<br>        self.original_cwd = os.getcwd()<br>        self.global_index = len(self.categories)*100 # initial value of global index<br>    <br>    def single_image_processing(self, filename, selected_categories=[0]):<br>        # method performs detection on an image (filename.jpg) and annotates it (filename.txt)<br>        img = self.open_img(path=filename) # open image<br>        result = self.predict_single_image(img=img) # object detection<br>        self.annotate_single_image(filename=filename, <br>                                   result=result, <br>                                   selected_categories=selected_categories) # annotaing file<br>    def open_img(self, path):<br>        #open image file<br>        return cv2.imread(path)<br><br>    def predict_single_image(self, img):<br>        # prediction on a single image, returns yolo reusults object<br>        return self.yolo_model.predict(img)<br>    <br>    def annotate_single_image(self, filename, result, selected_categories):<br>        # create &#39;.txt&#39; file with annotated bboxes corresponding to image file<br>        # in accordance with yolo requirements<br>        filename = filename.split(&#39;.&#39;)[0]<br>        filename += &#39;.txt&#39;<br>        label_file = open(file=filename, mode=&quot;w+&quot;)<br>        for box in result[0].boxes: # loop over detected objects&#39; bboxes<br>            cls = box.cls.cpu().numpy().astype(int)[0]<br>            xywhn = box.xywhn.cpu().numpy().astype(float)[0]<br>            label = f&#39;{cls} {xywhn[0]:0.6f} {xywhn[1]:0.6f} {xywhn[2]:0.6f} {xywhn[3]:0.6f} &#39;<br>            if cls in selected_categories:<br>                label_file.write(label)<br>                label_file.write(&#39;\n&#39;)<br>        label_file.close()<br>    <br>    def annotate_images(self):<br>        # method annotates images in their subdirs<br>        img_dir = self.original_cwd + &quot;\\&quot; + self.output_dir # path of images top dir<br>        img_subdirs = [x[0] for x in os.walk(img_dir)][1:] # list containing subdirs, &#39;0&#39;th element is the top dir, so eliminate it<br>        for img_subdir in img_subdirs: # loop over subdirs<br>            file_list = self.get_files_in_dir(path=img_subdir, filetype=&quot;.jpg&quot;) # get files in subdir<br>            for img_file in file_list: # loop over files<br>                img_file_path = img_subdir + &quot;\\&quot; + img_file<br>                self.single_image_processing(img_file_path) # annotate<br>    <br>    def get_files_in_dir(self, path, filetype=&quot;.jpg&quot;):<br>        # get list of files in dir with a given extension<br>        files = [f for f in os.listdir(path) if f.endswith(filetype)]<br>        return files<br>    <br>    def change_class_all_files(self):<br>        # method changes classes in annot files in their subdirs<br>        # so as they match our new classes<br>        img_dir = self.original_cwd + &quot;\\&quot; + self.output_dir # path of images top dir<br>        img_subdirs = [x[0] for x in os.walk(img_dir)][1:] # list containing subdirs, &#39;0&#39;th element is the top dir, so eliminate it<br>        category_index=0 # in ech subdir we will have distinct category index<br>        for img_subdir in img_subdirs: # loop over subdirs<br>            file_list = self.get_files_in_dir(path=img_subdir, filetype=&quot;.txt&quot;) # get annot files in subdir<br>            for img_file in file_list: # loop over files<br>                img_file_path = img_subdir + &quot;\\&quot; + img_file<br>                self.change_class_index(path=img_file_path, new_class=category_index)<br>            category_index += 1 # update index<br><br><br>    def change_class_index(self, path, new_class):<br>        # method changes class index in annot *.txt file<br>        f = open(file=path, mode=&quot;r+&quot;)<br>        lines = f.readlines()<br>        new_lines=[]<br>        for line in lines:<br>            new_lines.append(str(new_class)+line[1:])<br>        f.truncate(0)<br>        f.writelines(new_lines)<br>        f.close()<br>        # remove blank first line<br>        with open(path,&#39;r&#39;) as fin:<br>            data = fin.read().splitlines(True)<br>        with open(path, &#39;w&#39;) as fout:<br>            fout.writelines(data[1:])<br><br>    def rename_images(self):<br>        # method renames images (in each sub dir index starts from 1, and I need a global index)<br><br>        img_dir = self.original_cwd + &quot;\\&quot; + self.output_dir # path of images top dir<br>        img_subdirs = [x[0] for x in os.walk(img_dir)][1:] # list containing subdirs, &#39;0&#39;th element is the top dir, so eliminate it<br>        for img_subdir in img_subdirs: # loop over subdirs<br>            file_list = self.get_files_in_dir(path=img_subdir, filetype=&quot;.jpg&quot;) # get annot files in subdir<br>            for img_file in file_list: # loop over files<br>                img_file_path = img_subdir + &quot;\\&quot; + img_file<br>                new_img_file = img_file.split(&#39;_&#39;)[0] +&#39;_&#39; + str(self.global_index) + &#39;.jpg&#39;<br>                new_img_file_path = img_subdir + &#39;\\&#39; + new_img_file<br>                os.rename(img_file_path,new_img_file_path)<br>                self.global_index += 1<br>    <br>    def prepare_dataset_dir_structure(self):<br>        # method prepares dir structure for custom dataset<br>        if not os.path.exists(self.custom_dir):<br>            os.mkdir(self.custom_dir)<br>            os.mkdir(self.custom_dir + &quot;\\images&quot;)<br>            os.mkdir(self.custom_dir + &quot;\\images\\train&quot;)<br>            os.mkdir(self.custom_dir + &quot;\\images\\val&quot;)<br>            os.mkdir(self.custom_dir + &quot;\\labels&quot;)<br>            os.mkdir(self.custom_dir + &quot;\\labels\\train&quot;)<br>            os.mkdir(self.custom_dir + &quot;\\labels\\val&quot;)<br><br>    def prepare_yaml_file(self, yaml_filename=&quot;dataset.yaml&quot;):<br>        # method prepares yaml file for YOLO8<br>        yaml_file = []<br>        yaml_file.append(&quot;# Train/val sets as path/to/imgs \n&quot;)<br>        yaml_file.append(&quot;path: &quot; + self.original_cwd + &quot;/&quot; +self.custom_dir+&quot; # dataset root dir\n&quot;)<br>        yaml_file.append(&quot;train: images/train # train images (relative to &#39;path&#39;)\n&quot;)<br>        yaml_file.append(&quot;val: images/val # val images (relative to &#39;path&#39;)\n&quot;)<br>        yaml_file.append(&quot;          \n&quot;)<br>        yaml_file.append(&quot;# Classes (&quot;+str(len(self.categories))+&quot; classes)\n&quot;)<br>        yaml_file.append(&quot;names:\n&quot;)<br>        for i in range(len(self.categories)):<br>            yaml_file.append(&quot;    &quot;+str(i)+&quot;: &quot;+self.categories[i]+&quot;\n&quot;)<br>        with open(yaml_filename, &#39;w&#39;) as fout:<br>            fout.writelines(yaml_file)<br>    <br>    def copy_files_to_dirs_random(self):<br>        # method copies files to respective dirs - prepare YOLO dataset<br><br>        img_dir = self.original_cwd + &quot;\\&quot; + self.output_dir # path of images top dir<br>        img_subdirs = [x[0] for x in os.walk(img_dir)][1:] # list containing subdirs, &#39;0&#39;th element is the top dir, so eliminate it<br>        <br>        img_dest_train = self.original_cwd + &quot;\\&quot; + self.custom_dir + &quot;\\images\\train&quot; # destination dir<br>        img_dest_val = self.original_cwd + &quot;\\&quot; + self.custom_dir + &quot;\\images\\val&quot;<br><br>        lbl_dest_train = self.original_cwd + &quot;\\&quot; + self.custom_dir + &quot;\\labels\\train&quot; # destination dir<br>        lbl_dest_val = self.original_cwd + &quot;\\&quot; + self.custom_dir + &quot;\\labels\\val&quot;<br>        <br>        <br>        train_val_switch = int(self.num_imgs * self.train_val_split_ratio) - 1 # index to switch destination dir from train to val<br>        <br>        for img_subdir in img_subdirs: # loop over subdirs<br>            file_list = self.get_files_in_dir(path=img_subdir, filetype=&quot;.jpg&quot;) # get files in subdir<br>            <br>            img_dest_dir = img_dest_train # initial value<br>            lbl_dest_dir = lbl_dest_train <br>            train_val_idx = 0 # monitor number of files<br>            for img_file in file_list: # loop over files<br>                random_val = random.random() # random value to decide where to copy files (img+txt)<br>                print(random_val)<br>                img_file_path = img_subdir + &quot;\\&quot; + img_file # source image path<br>                lbl_file = img_file.split(&quot;.&quot;)[0] + &quot;.txt&quot;<br>                lbl_file_path = img_subdir + &quot;\\&quot; + lbl_file<br>                if random_val &gt; self.train_val_split_ratio:<br>                    img_dest_dir = img_dest_val<br>                    lbl_dest_dir = lbl_dest_val<br>                else:<br>                    img_dest_dir = img_dest_train <br>                    lbl_dest_dir = lbl_dest_train <br>                shutil.copy(img_file_path, img_dest_dir) # copy into dest dir<br>                shutil.copy(lbl_file_path, lbl_dest_dir) # copy into dest dir<br>                train_val_idx += 1<br><br># MAIN PROGRAM<br><br>yd = CustomDataset()<br>yd.prepare_dataset_dir_structure()<br>yd.prepare_yaml_file()<br>yd.rename_images()<br>yd.annotate_images()<br>yd.change_class_all_files()<br>yd.copy_files_to_dirs_random()</pre><h3>4. Train dataset</h3><p>This is the longest but also the easiest part ;). The good news is that you do not have to train all at once, say 100 epochs. It may be done in chunks, say 10 epochs a time (important if you have a limited GPU access, or have to do it on your laptop) — YOLO, after each run (say 10 epochs one), saves “last.pt” and “best.pt” — the weights after last epoch and the best weights in the run (based on validation dataset). So after a run you can use the “best.pt” weights a starting point for next run doing it in an iterative way — please do remember, that after each run you have to copy it from run’s directory into the directory you run yolo from. Anyway, the syntax is shown below, enought to paste it into the terminal:</p><pre># first run, using &#39;yolov8n.pt&#39; as starting point<br>yolo task=detect mode=train model=yolov8n.pt data=dataset.yaml epochs=5 imgsz=640</pre><pre># second and subsequent runs, using updated &#39;best.pt&#39;<br>yolo task=detect mode=train model=best.pt data=dataset.yaml epochs=5 imgsz=640</pre><h3>5. Enjoy</h3><p>The outlined method is not general, rather specific to get datasets able to distinguish between subsets of the sets available in trained datasets one has access to, like detecting construction workers wearing/not wearing helmets or decide is it a bird or a drone. But, as I’ve learned empirically, if one is creative there is a whole spectrum of possibilities. Therefore, happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=295f5c9ccfb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast and simple deterministic image super-resolution with OpenCV]]></title>
            <link>https://medium.com/@telega.slawomir.ai/fast-and-simple-deterministic-image-super-resolution-with-opencv-bb1cda56f6d9?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb1cda56f6d9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[super-resolution]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Thu, 30 May 2024 09:30:53 GMT</pubDate>
            <atom:updated>2024-05-30T09:30:53.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzOtLG9yvvkz8dTg-4qR0w.jpeg" /><figcaption><a href="https://unsplash.com/@robertbock">https://unsplash.com/@robertbock</a></figcaption></figure><h3>Introduction</h3><p>There is quite a choice of deep learning algorithms allowing for boosting image/video resolution and some of them perform an amazing job doing so. But the problem is, that there are circumstances, when the result does not have to be extremally eye-pleasing — it suffices that it makes the details visible. For instance, the IR footage from CCTV/security cams is often distorted and blurred, making it difficult to even distinguish objects of interest from the background. At the same time, usually the cameras are not attached to the SOTA computer with a powerful GPU onboard -rather a modest PC with integrated graphics. Therefore, the need arises for a simple, classical (deterministic) solution that will fulfill two conditions: 1) show more details on the output than on the input and 2) be as fast as possible, even on a weak CPU.</p><h3>Theoretical outline</h3><p>Searching for a solution, I’ve came across the research performed by Seiichi Gohshi [1], who invented rather ingenious way to add details/edges to an image using only the very image. In short words, the idea is to introduce new, high-frequency elements created from existing image — i.e. create sharper edges. The way to do it, proposed by Gohshi, is quite straightforward: 1) take an image (IMG) and upscale it two-times, 2) pass it through a high pass filter to separate high-frequency part (HF), 3) use a non-linear transformation on the HF (proposed transformation is a simple cubic function y=x**3) and finally 4) perform a weighted sum of IMG and HF. What does the trick in passing HF through a NL function, introducing that way components with frequency about 3 times higher, than those already present in the image.</p><h3>Implementation</h3><p>I’ve decided to implement the above in Python, using OpenCV and Numpy libraries for matrix operations (scalling, adding, filtering, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*x23zOj1BHOSGHpii_dvZDg.jpeg" /><figcaption>initial image — fragment, cut from the one above</figcaption></figure><p>The code is simple. First I define some utility functions:</p><pre>import numpy as np<br>import cv2<br><br>def lanczos_resize(img, scale_factor):<br>    # resize img by a scale_factor using Lanczos interpolation<br>    return cv2.resize(img, None, <br>                      fx=scale_factor, fy=scale_factor,<br>                      interpolation=cv2.INTER_LANCZOS4)<br><br>def read_img(filename, monochrome=False):<br>    # read image<br>    if monochrome:<br>        return cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2GRAY)<br>    else:<br>        return cv2.imread(filename)<br><br>def laplacian_filter(img):<br>    # Laplacian sharpening filter<br>    return cv2.Laplacian(img, -1, ksize=5, scale=1, <br>                          delta=0, borderType=cv2.BORDER_DEFAULT)</pre><p>Next, I read an image and scale it to double the size (both horizontally and vertically), using Lanczos interpolation and scale it to (-1.0, 1.0) range.</p><pre># load and resize<br>img = lanczos_resize(read_img(&quot;img.jpg&quot;, monochrome=True), 2)<br><br># scale from 0-255 to -1, 1<br>img = 2 * (img / 255.) - 1.</pre><p>Next I separate the high-frequency components of an image filtering it with a 5-element Laplacian kernel and raise it to the third (or second, depending on the image) power obtaining therefore new, higher frequency elements (as Gohshi shows, it approximately introduces the components of frequency three times bigger than maximum frequency already present in the image). The result is normalized — divided by the maximum pixel value in the image (can be quite large, after applying Laplacian and raising to a third power)</p><pre># get high frequency part and raise it to the second power<br>img_hf = (laplacian_filter(img))**2<br># normalize<br>img_hf /= np.max(img_hf)</pre><p>Last thing to do is to perform a weighted sum of the original image and boosted frequency part.</p><pre># sum up<br>img_sr = img + 2.0* img_hf<br># move back to -1., 1. range<br>img_sr = (img_sr + 1.)/2.</pre><p>Below one may observe the result, but I encourage to try and code it, because the difference is more visible in higher res, without the artifacts appearing due to compression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*bQEOgD3H-g8NcoloqsMJ6Q.png" /><figcaption>Boosted resolution</figcaption></figure><h3>Summary</h3><p>Although the result, in some cases, may not be clearly visible or the look may not be so very much eye-pleasing, it has been proved in the subject’s literature, that the frequency range of the image gets expanded (as should be visible after visualizing the magnitude spectrum after performing 2D FFT on the image).</p><p>In original formulation appeares a problem — addition of HF part introduces artifacts to lower frequency regions of the original image. There exists research papers dealing with it by, roughly speaking, adding the boosted part only to some areas, which already were high-frequency. It is an interesting solution, but as I wanted something simple and as fast as possible, with less consideration regarding aesthetics.</p><p>To sum up, I suppose that deterministic super-resolution techniques will not be able to achieve results accesible to deep-learning ones, like GAN (Generative Adversial Network-based or ZSSR (Zero Shot Super Resolution). But they are much faster and simpler to code, which makes them perfect in the situations, I’ve outlined in the introduction.</p><p>Full code is available at <a href="https://github.com/SlawekTT/SR_simple">https://github.com/SlawekTT/SR_simple</a></p><p>Happy coding</p><h3>References</h3><ol><li>Gohshi, S. (2013). A New Signal Processing Method for Video Image-Reproduce the Frequency Spectrum Exceeding the Nyquist Frequency Using a Single Frame of the Video Image. In: The Era of Interactive Media. Springer, New York, NY. <a href="https://doi.org/10.1007/978-1-4614-3501-3_49">https://doi.org/10.1007/978-1-4614-3501-3_49</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1cda56f6d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YOLO8 basics: plotting bboxes]]></title>
            <link>https://medium.com/@telega.slawomir.ai/yolo8-basics-plotting-bboxes-e50a8f3e5227?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50a8f3e5227</guid>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[ultralytics]]></category>
            <category><![CDATA[yolo8]]></category>
            <category><![CDATA[bounding-box]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 11:52:46 GMT</pubDate>
            <atom:updated>2024-04-11T11:52:46.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>YOLO8 from Ultralytics is a state of the art package in the field of object detection (among other capabilities, like segmentation, pose estimation, tracking…). It’s extremally efficient, precise and easy-to-use. Still, if you intends to use it in a bit more custom way, you have to get a grip of the <em>results</em> object. In this tutorial I intend to show the very basic operation — i.e. getting the information from results and plotting them in a form of annotated bounding boxes.</p><h3>Code, step by step</h3><p>We start with necessary imports and a simple function returning a basic YOLO pretrained model used for object detection (<em>yolov8n.pt</em> is the smallest ready-to-use net, trained on COCO dataset). Model fusing allows for a faster processing, even on CPU.</p><pre>from ultralytics import YOLO<br>import numpy as np<br>import cv2<br><br>def get_model(): # prepare the model<br>    model = YOLO(&#39;yolov8n.pt&#39;)<br>    model.fuse()<br>    return model</pre><p>Getting the predictions is easy — just running the inference. And later on we have to plot bounding boxes and show results on the screen.</p><pre>results = get_model()(&#39;cat_2.jpg&#39;) # run inference<br>img = plot_bboxes(results) # plot annotated bboxes<br>cv2.imshow(&#39;img&#39;, img) # show annotated image<br>cv2.waitKey(0) # wait for a keypressed<br>cv2.destroyAllWindows() # clear windows</pre><p>Now for the main function, plotting the bounding boxes and annotating them. See the detailed explanation below the code.</p><pre>def plot_bboxes(results):<br>    img = results[0].orig_img # original image<br>    names = results[0].names # class names dict<br>    scores = results[0].boxes.conf.numpy() # probabilities<br>    classes = results[0].boxes.cls.numpy() # predicted classes<br>    boxes = results[0].boxes.xyxy.numpy().astype(np.int32) # bboxes<br>    for score, cls, bbox in zip(scores, classes, boxes): # loop over all bboxes<br>        class_label = names[cls] # class name<br>        label = f&quot;{class_label} : {score:0.2f}&quot; # bbox label<br>        lbl_margin = 3 #label margin<br>        img = cv2.rectangle(img, (bbox[0], bbox[1]),<br>                            (bbox[2], bbox[3]),<br>                            color=(0, 0, 255),<br>                            thickness=1)<br>        label_size = cv2.getTextSize(label, # labelsize in pixels <br>                                     fontFace=cv2.FONT_HERSHEY_SIMPLEX, <br>                                     fontScale=1, thickness=1)<br>        lbl_w, lbl_h = label_size[0] # label w and h<br>        lbl_w += 2* lbl_margin # add margins on both sides<br>        lbl_h += 2*lbl_margin<br>        img = cv2.rectangle(img, (bbox[0], bbox[1]), # plot label background<br>                             (bbox[0]+lbl_w, bbox[1]-lbl_h),<br>                             color=(0, 0, 255), <br>                             thickness=-1) # thickness=-1 means filled rectangle<br>        cv2.putText(img, label, (bbox[0]+ lbl_margin, bbox[1]-lbl_margin), # write label to the image<br>                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,<br>                    fontScale=1.0, color=(255, 255, 255 ),<br>                    thickness=1)<br>    return img</pre><p>Lines 1–5: given the results object, we read from it the original image, dictionary of class names and corresponding indexes, probability scores of detected objects and their class indices and bounding boxes. If one uses the GPU, there will be a need to use <em>.cpu()</em> before<em> .numpy()</em>, to transfer the results into CPU’s memory.</p><p>Line 6: main loop over scores, indices and corresponding bounding boxes — simply speaking we loop over detected objects, one by one</p><p>Line 7: get class name from a dict lookup</p><p>Line 8–9: prepare label for bbox annotation and define a margin (so as the label looks nicer with some space around it)</p><p>Line 10–13: we plot the bounding box using openCV’s rectangle, using two points : upper left corner (bbox[0], bbox[1]) and lower right corner (bbox[2], bbox[3]), color is defined by components, but keep in mind that openCV uses BGR format in contarary to the standard RGB one.</p><p>Line 14–19: we obtain the estaimation of the size of a rectangle that will fit the label size, and we add margin value to each side of the given rectangle, to give the text some space around.</p><p>Line 20–23: plot the label’s background</p><p>Line 24–27: put the text on top and return the updated image</p><p>See below the example of running this code on a beautiful picture taken by Alexander London (<a href="https://unsplash.com/@alxndr_london">https://unsplash.com/@alxndr_london</a>), shared on Unsplash.</p><figure><img alt="https://unsplash.com/@alxndr_london" src="https://cdn-images-1.medium.com/max/480/1*b9eYoheoCAtQT4eXaOPJ_Q.jpeg" /></figure><h3>Summary</h3><p>As seen above, it is quite straightforward to plot bounding boxes from YOLO’s predictions. In the nearest future I plan to show how to plot segmentation masks and estimated poses. For the sake of completness I attach the full code in one piece below:</p><pre>from ultralytics import YOLO<br>import numpy as np<br>import cv2<br><br>def get_model(): # prepare the model<br>    model = YOLO(&#39;yolov8n.pt&#39;)<br>    model.fuse()<br>    return model<br><br>def plot_bboxes(results):<br>    img = results[0].orig_img # original image<br>    names = results[0].names # class names dict<br>    scores = results[0].boxes.conf.numpy() # probabilities<br>    classes = results[0].boxes.cls.numpy() # predicted classes<br>    boxes = results[0].boxes.xyxy.numpy().astype(np.int32) # bboxes<br>    for score, cls, bbox in zip(scores, classes, boxes): # loop over all bboxes<br>        class_label = names[cls] # class name<br>        label = f&quot;{class_label} : {score:0.2f}&quot; # bbox label<br>        lbl_margin = 3 #label margin<br>        img = cv2.rectangle(img, (bbox[0], bbox[1]),<br>                            (bbox[2], bbox[3]),<br>                            color=(0, 0, 255),<br>                            thickness=1)<br>        label_size = cv2.getTextSize(label, # labelsize in pixels <br>                                     fontFace=cv2.FONT_HERSHEY_SIMPLEX, <br>                                     fontScale=1, thickness=1)<br>        lbl_w, lbl_h = label_size[0] # label w and h<br>        lbl_w += 2* lbl_margin # add margins on both sides<br>        lbl_h += 2*lbl_margin<br>        img = cv2.rectangle(img, (bbox[0], bbox[1]), # plot label background<br>                             (bbox[0]+lbl_w, bbox[1]-lbl_h),<br>                             color=(0, 0, 255), <br>                             thickness=-1) # thickness=-1 means filled rectangle<br>        cv2.putText(img, label, (bbox[0]+ lbl_margin, bbox[1]-lbl_margin), # write label to the image<br>                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,<br>                    fontScale=1.0, color=(255, 255, 255 ),<br>                    thickness=1)<br>    return img<br><br>results = get_model()(&#39;cat_2.jpg&#39;)<br>img = plot_bboxes(results)<br>cv2.imshow(&#39;img&#39;, img)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50a8f3e5227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON to YOLO Dataset Converter]]></title>
            <link>https://medium.com/@telega.slawomir.ai/json-to-yolo-dataset-converter-9e9e643a31a7?source=rss-0866c1a979c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e9e643a31a7</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[yolov8]]></category>
            <dc:creator><![CDATA[Slawomir Telega, PhD]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 15:06:31 GMT</pubDate>
            <atom:updated>2024-03-11T15:06:31.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZMHgMsXR1GQ9EmDYH9r6A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hannynaibaho?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Hanny Naibaho</a> on <a href="https://unsplash.com/photos/two-yellow-bus-beside-street-during-night-time-oTP4xd9SAkc?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>At a certain point, growing as an AI developer, one has to move away from a safe space of tutorials and security nets spanned by somebody else’s datasets and generate one. It is just a moment before an aspiring developer comes to understand, that 90% percent of the job, for most of us, is data wrangling, and not developing new network architectures… As the process can be rather boaring, I intend a short script, allowing to convert JSON annotated images (say, an output of VGG VAI [1]) into YOLO’s img/txt dual format. And I do realize, there is quite a number of packages/repositiories able to do so, but I strongly believe in learning by doing, plus knowing the details makes your code more bug-proof.</p><p>Enough said, let’s get coding.</p><h3>Theory</h3><p>JSON annotation (eg. output from VGG VAI) usually stores bounding boxes written in a format <em>(x_min, y_min, width, height)</em> where <em>(x_min, y_min)</em> are the coordinates of the upper left corner of a bounding box, and (width, height) are self-explainatory ;). All the above are given in absolute values (i.e. in pixels). JSON is a hierarchical format (think UML/XML), with (in this case) top category being an image. In an image we’ve got (among others) so called regions, corresponding to bounding boxes. Each of the bounding boxes is described by a category_id (for classification, correspond to the object which is surronded by a bounding box) and <em>(x_min, y_min, w, h)</em> coordinates (If you’re ahving a hard time imagining the structure of JSON, you might consider using a <em>pprint </em>package or an editior capable of displaying JSON in expanded form).</p><p>YOLO, on the other hand, uses much more human-readable format. Suppose we have an image <em>cats.jpg</em>. To have a YOLO-compilant annotations, we are to create <em>cats.txt</em> file, containing a row for each bounding box with five numbers:<em> category_id, x_c, y_c, width, height</em>. Here <em>(x_c, y_c)</em> are the relative coordinates of the centre of bounding box rectangle, while <em>(width, height) </em>are now also relative. All four values stay in (0, 1) range. <em>Relative</em> means here, they are claculated with respect to the image’s shape.</p><p>To be less criptic, let’s take a simple example and consider a point of cooridinates (128, 288) ploted on an image of 640x480 resolution. The relative (i.e. in respect to image’s shape) coordianates wil be equal to 128/640 and 288/480, which can be further simplified to 0.2 and 0.6. Therefore, in this case absolute cooridinates (128, 288), if the image size is 640x480, correspond to (0.2, 0.6). The same math goes with bboxes, only more writing…</p><h3>The Code</h3><p>As usual, we start with the necessary imports:</p><pre>import json, cv2 # import json reader and openCV</pre><p>Next we define helper functions. First one opens the JSON file and loads the content into an JSON object:</p><pre>def read_json(json_file):<br># read data from json<br>    with open(json_file) as f:<br>        json_obj = json.load(f)<br>    return json_obj</pre><p>Top level in JSON hierarchy is an image identifier composed of image’s filename (without extension) and bytesize of the very image — at least we can be sure it’s unique, and allows to browse description of each image separately. The following function retrives those identifiers (filename+size) and stores them in a list (<em>img_names</em>)</p><pre>def get_img_names(json_obj):<br># get image names from json - top level in hierarchy<br>    img_names = []<br>    for name in list(json_obj):<br>        img_names.append(name)<br>    return img_names</pre><p>As you may presume, at a certain point we’re gonna need image spatial dimensions:</p><pre>def get_img_shape(img_file):<br># get image shape<br>    img = cv2.imread(img_file)<br>    return img.shape # (height,width, channels)</pre><p>The above will be used to calculate relative bounding box coordinates:</p><pre>def calc_centroids(bbox, img_shape):<br># convert from absolute (x_min, y_min, w, h) <br># to relative (x_c_rel, y_c_rel, rel_w, rel_h) (in range (0,1))<br>    xmin, ymin, w, h = bbox<br>    img_height, img_width = img_shape[:2]<br>    <br>    # get lower right corner cooridnates<br>    xmax = xmin + w <br>    ymax = ymin + h<br>    <br>    # calcualte centre of the bounding box<br>    x_c = (xmin + xmax) // 2<br>    y_c = (ymin + ymax) // 2<br>    <br>    # get relative values + round to three digits, to look nice<br>    x_c_rel = round(x_c / img_width, 3)<br>    y_c_rel = round(y_c / img_height, 3)<br>    <br>    w_rel = round(w / img_width, 3)<br>    h_rel = round(h / img_height, 3)<br>    <br>    # return relative bounding box<br>    return (x_c_rel, y_c_rel, w_rel, h_rel)</pre><p>During the execution, bounding box coordinates will be read from JSON into respective lists (<em>xmin, ymin, w, h</em>). The following function converts these lists into a list of bounding boxes:</p><pre>def create_bbox(xmin, ymin, w, h):<br># create list of bbox tuples from x, y, w, h lists<br>    bboxs = []<br>    num_bb = len(xmin)<br>    for i in range(num_bb):<br>        bboxs.append((xmin[i], ymin[i], w[i], h[i]))<br>    return bboxs</pre><p>In the end, we have to write relative bounding boxes and corresponding category id into a *.txt file for each image:</p><pre>def write_yolo_txt(rel_bboxs, img_class, img_filename):<br># write txt file for a given image<br>    txt_filename = img_filename.split(&#39;.&#39;)[0]+&quot;.txt&quot; # generate txt file corresponding to image filename<br>    num_annots = len(img_class) # get number of bboxes<br>    with open(txt_filename,&quot;w&quot;) as f: # write to a file<br>        for i in range(num_annots): # for each bbox<br>            # compose a row<br>            row = str(img_class[i]) + &quot;, &quot; + str(rel_bboxs[i][0]) + &quot;, &quot; + str(rel_bboxs[i][1])<br>            row = row +  &quot;, &quot; + str(rel_bboxs[i][2]) + &quot;, &quot; + str(rel_bboxs[i][3]) + &quot;\n&quot;<br>            # and write it to the file<br>            f.write(row)</pre><p>At this point we have everything needed to put together a converter:</p><pre>def convert_to_yolo(json_file,img_dir):<br>    json_obj = read_json(json_file) # read JSON<br>    img_names = get_img_names(json_obj) # get top category identifiers<br>    <br>    for img in img_names: # loop over files<br>        # define lists for bbox params<br>        img_class = []<br>        xmin = []<br>        ymin = []<br>        width = []<br>        height = []<br>        #loop over regions in json (for a given image)<br>        # to get bboxes coords<br>        for region in json_obj[img][&#39;regions&#39;]:<br>            dict_key = (next(iter(region[&#39;region_attributes&#39;])))<br>            img_class.append(region[&#39;region_attributes&#39;][dict_key])<br>            xmin.append(region[&#39;shape_attributes&#39;][&#39;x&#39;])<br>            ymin.append(region[&#39;shape_attributes&#39;][&#39;y&#39;])<br>            width.append(region[&#39;shape_attributes&#39;][&#39;width&#39;])<br>            height.append((region[&#39;shape_attributes&#39;][&#39;height&#39;]))<br>            <br>        # get img filename<br>        img_filename = json_obj[img][&#39;filename&#39;]<br>        # read img shape<br>        img_shape = get_img_shape(img_dir+img_filename)<br>        # generte bboxes (xmin, ymin, w, h) absolute values<br>        bboxs = create_bbox(xmin, ymin, width, height)<br>        rel_bboxs = [] # an embboxespty list for relative <br>        # calculate relative bboxes<br>        for bbox in bboxs:<br>            rel_bboxs.append(calc_centroids(bbox, img_shape))<br>        # and write annotations in YOLO format<br>        write_yolo_txt(rel_bboxs, img_class, img_filename)<br>    return 0</pre><p>Only thing that remains to be done is to define paths and run the code:</p><pre>img_dir = &quot;images/&quot;<br>json_file = &quot;annotations/via_project.json&quot;<br>convert_to_yolo(json_file, img_dir)</pre><p>Hope, you’ll find this piece of code useful and maybe even helpfull. If you have any questions, please do not hesitate to contact me. Till then, happy coding.</p><p>Cheers</p><p>S.</p><h3>Full code</h3><p>For the sake of clarity and completeness, I attach the full code in one piece, below.</p><pre>import json, cv2 # import json reader and openCV<br><br>def read_json(json_file):<br># read data from json<br>    with open(json_file) as f:<br>        json_obj = json.load(f)<br>    return json_obj<br><br>def get_img_names(json_obj):<br># get image names from json - top level in hierarchy<br>    img_names = []<br>    for name in list(json_obj):<br>        img_names.append(name)<br>    return img_names<br><br>def get_img_shape(img_file):<br># get image shape<br>    img = cv2.imread(img_file)<br>    return img.shape # (height,width, channels)<br><br>def calc_centroids(bbox, img_shape):<br># convert from absolute (x_min, y_min, w, h) <br># to relative (x_c_rel, y_c_rel, rel_w, rel_h) (in range (0,1))<br>    xmin, ymin, w, h = bbox<br>    img_height, img_width = img_shape[:2]<br>    <br>    # get lower right corner cooridnates<br>    xmax = xmin + w <br>    ymax = ymin + h<br>    <br>    # calcualte centre of the bounding box<br>    x_c = (xmin + xmax) // 2<br>    y_c = (ymin + ymax) // 2<br>    <br>    # get relative values + round to three digits, to look nice<br>    x_c_rel = round(x_c / img_width, 3)<br>    y_c_rel = round(y_c / img_height, 3)<br>    <br>    w_rel = round(w / img_width, 3)<br>    h_rel = round(h / img_height, 3)<br>    <br>    # return relative bounding box<br>    return (x_c_rel, y_c_rel, w_rel, h_rel)<br><br>def create_bbox(xmin, ymin, w, h):<br># create list of bbox tuples from x, y, w, h lists<br>    bboxs = []<br>    num_bb = len(xmin)<br>    for i in range(num_bb):<br>        bboxs.append((xmin[i], ymin[i], w[i], h[i]))<br>    return bboxs<br><br>def write_yolo_txt(rel_bboxs, img_class, img_filename):<br># write txt file for a given image<br>    txt_filename = img_filename.split(&#39;.&#39;)[0]+&quot;.txt&quot; # generate txt file corresponding to image filename<br>    num_annots = len(img_class) # get number of bboxes<br>    with open(txt_filename,&quot;w&quot;) as f: # write to a file<br>        for i in range(num_annots): # for each bbox<br>            # compose a row<br>            row = str(img_class[i]) + &quot;, &quot; + str(rel_bboxs[i][0]) + &quot;, &quot; + str(rel_bboxs[i][1])<br>            row = row +  &quot;, &quot; + str(rel_bboxs[i][2]) + &quot;, &quot; + str(rel_bboxs[i][3]) + &quot;\n&quot;<br>            # and write it to the file<br>            f.write(row)<br><br>def convert_to_yolo(json_file,img_dir):<br>    json_obj = read_json(json_file) # read JSON<br>    img_names = get_img_names(json_obj) # get top category identifiers<br>    <br>    for img in img_names: # loop over files<br>        # define lists for bbox params<br>        img_class = []<br>        xmin = []<br>        ymin = []<br>        width = []<br>        height = []<br>        #loop over regions in json (for a given image)<br>        # to get bboxes coords<br>        for region in json_obj[img][&#39;regions&#39;]:<br>            dict_key = (next(iter(region[&#39;region_attributes&#39;])))<br>            img_class.append(region[&#39;region_attributes&#39;][dict_key])<br>            xmin.append(region[&#39;shape_attributes&#39;][&#39;x&#39;])<br>            ymin.append(region[&#39;shape_attributes&#39;][&#39;y&#39;])<br>            width.append(region[&#39;shape_attributes&#39;][&#39;width&#39;])<br>            height.append((region[&#39;shape_attributes&#39;][&#39;height&#39;]))<br>            <br>        # get img filename<br>        img_filename = json_obj[img][&#39;filename&#39;]<br>        # read img shape<br>        img_shape = get_img_shape(img_dir+img_filename)<br>        # generte bboxes (xmin, ymin, w, h) absolute values<br>        bboxs = create_bbox(xmin, ymin, width, height)<br>        rel_bboxs = [] # an embboxespty list for relative <br>        # calculate relative bboxes<br>        for bbox in bboxs:<br>            rel_bboxs.append(calc_centroids(bbox, img_shape))<br>        # and write annotations in YOLO format<br>        write_yolo_txt(rel_bboxs, img_class, img_filename)<br>    return 0<br><br>img_dir = &quot;images/&quot;<br>json_file = &quot;annotations/via_project.json&quot;<br>convert_to_yolo(json_file, img_dir)</pre><h3><em>References</em></h3><ol><li><em>Abhishek Dutta and Andrew Zisserman. 2019. </em><a href="https://www.robots.ox.ac.uk/~vgg/software/via/docs/dutta2019vgg_arxiv.pdf"><em>The VIA Annotation Software for Images, Audio and Video</em></a><em>. In Proceedings of the 27th ACM International Conference on Multimedia (MM ’19), October 21–25, 2019, Nice, France. ACM, New York, NY, USA, 4 pages. </em><a href="https://doi.org/10.1145/3343031.3350535."><em>https://doi.org/10.1145/3343031.3350535.</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e9e643a31a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>