<?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 Yerdaulet Zhumabay on Medium]]></title>
        <description><![CDATA[Stories by Yerdaulet Zhumabay on Medium]]></description>
        <link>https://medium.com/@yerdaulet.zhumabay?source=rss-ae8e391d6bf3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*guxL_vq6aysN1bYa.jpg</url>
            <title>Stories by Yerdaulet Zhumabay on Medium</title>
            <link>https://medium.com/@yerdaulet.zhumabay?source=rss-ae8e391d6bf3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:43:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yerdaulet.zhumabay/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[Anchor Boxes Generation using K-Means clustering]]></title>
            <link>https://medium.com/@yerdaulet.zhumabay/generating-anchor-boxes-by-k-means-82f11c690b82?source=rss-ae8e391d6bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f11c690b82</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[Yerdaulet Zhumabay]]></dc:creator>
            <pubDate>Thu, 08 Dec 2022 11:23:10 GMT</pubDate>
            <atom:updated>2022-12-26T11:34:33.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FjfQb-_H3yZwBXXl9uSelQ.png" /><figcaption>Bird</figcaption></figure><p>This article aims to implement K-Means algorithm for generation anchor boxes for object detection architectures, which is an important concept for detecting small or unusual objects in the image.</p><h3><strong>What is anchor box?</strong></h3><blockquote><strong><em>Anchor boxes</em> </strong>are a set of predefined bounding boxes of a certain height and width. These boxes are defined to capture the scale and aspect ratio of specific object classes you want to detect and are typically chosen based on object sizes in your training datasets. During detection, the predefined anchor boxes are tiled across the image. The network predicts the probability and other attributes, such as background, intersection over union (IoU) and offsets for every tiled anchor box. The predictions are used to refine each individual anchor box. You can define several anchor boxes, each for a different object size. Anchor boxes are fixed initial boundary box guesses.</blockquote><h3><strong>About Dataset</strong></h3><p><a href="http://www.vision.caltech.edu/datasets/cub_200_2011/">Caltech-UCSD Birds 200–2011</a> (CUB-200–2011) is an extended version of the CUB-200 dataset, with roughly double the number of images per class and new part location annotations.</p><ul><li>Number of categories: 200</li><li>Number of images: 11,788</li><li>Annotations per image: 15 Part Locations, 312 Binary Attributes, 1 Bounding Box</li></ul><h3>Steps of generating Anchor boxes</h3><ol><li>Prepare the bounding boxes</li><li>Define distance calculation function</li><li>Implement K-Means alghorithm</li><li>Train and Evaluate the results</li></ol><h3>Step 1. Prepare the bounding boxes</h3><p>We cannot rely on the original bounding boxes cuz image sizes are different. At first, should define a specific image size for all images, it might be (512, 512) or (640, 640) according to the input of the network. Resize the image by keeping the aspect ratio and additionally pad zeros to these areas where no pixel values fit the specified size. Finally redefine bounding boxes according to the resized, padded image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*S6s1URKE6jJtIKMAyuUoMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*SHxWSSc48O-ntDy3Wu7a8Q.png" /><figcaption>Example of image resizing by keeping aspect ratio and bounding box redefinition</figcaption></figure><p>Python code:</p><pre>import tqdm<br>import torch, cv2<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>from PIL import Image<br>from torchvision.ops import box_iou</pre><pre>image_paths = np.loadtxt(image_file_paths, dtype=str) # all image paths<br>bboxes_file_path = &quot;path to the bboxes.txt&quot;<br>bboxes = torch.tensor(np.loadtxt(bboxes_file_path, dtype=int, delimiter=&quot; &quot;, ndmin=2)[:, 1:]) # Take only x, y, w, h <br>bboxes[:, 2] = bboxes[:, 2] + bboxes[:, 0] # get corner point<br>bboxes[:, 3] = bboxes[:, 3] + bboxes[:, 1] # get corner point</pre><pre>def scale_bbox(bbox, image, o_shape):<br>    W, H, C = o_shape<br>    w, h, c = image.shape<br>    Wratio = w/W<br>    Hratio = h/H<br>    ratioList = [Hratio, Wratio, Hratio, Wratio]<br>    bbox = [int(a * b) for a, b in zip(bbox, ratioList)]<br>    return bbox<br><br># Function that returns redefined bbox<br>def function(image, bboxs, base=512):<br>    H, W, C = image.shape<br>    if H &gt; W:<br>        height_persentage = float(base/H)<br>        width_size = int(W*height_persentage)<br>        resized_image = cv2.resize(image, (width_size, base), interpolation=cv2.INTER_CUBIC)<br>        h, w, c = resized_image.shape<br>        bbox = scale_bbox(bboxs, resized_image, (H, W, C))<br>        width1 = (base - w) // 2<br>        width2 = (base - w) - width1<br>        bbox = [bbox[0]+width1, bbox[1], bbox[2]+width2, bbox[3]]<br>        <br>        # Symmetric Padding<br>        mask = np.array(np.zeros(shape=(base, width1, C)), dtype=int)<br>        resized_image = np.concatenate((resized_image, mask), axis=1)<br><br>        mask = np.array(np.zeros(shape=(base, width2, C)), dtype=int)<br>        resized_image = np.concatenate((mask, resized_image), axis=1)<br>        # display(resized_image, bbox)<br>        <br>    else:<br>        width_percentage = float(base/W)<br>        height_size = int(H*width_percentage)<br>        resized_image = cv2.resize(image, (base, height_size), interpolation=cv2.INTER_CUBIC)<br>        h, w, c = resized_image.shape<br>        bbox = scale_bbox(bboxs, resized_image, (H, W, C))<br>        height1 = (base - h) // 2<br>        height2 = (base - h) - height1<br>        bbox = [bbox[0], bbox[1]+height1, bbox[2], bbox[3]+height2]<br>        <br>        # Symmetric Padding<br>        mask = np.array(np.zeros(shape=(height1, base, C)), dtype=int)<br>        resized_image = np.concatenate((resized_image, mask))<br>        <br>        mask = np.array(np.zeros(shape=(height2, base, C)), dtype=int)<br>        resized_image = np.concatenate((mask, resized_image))<br>        # display(resized_image, bbox)<br>    <br>    return bbox<br><br><br>bbox = function(image, bbox)</pre><pre>redefined_bboxes = []<br><br>for idx in tqdm.trange(len(image_paths)):<br>    image = np.array(Image.open(images_dir_path + image_paths[idx][1]).convert(&quot;RGB&quot;))<br>    bbox = bboxes[idx].numpy()<br>    bbox = function(image, bbox)<br>    redefined_bboxes.append(bbox)<br>redefined_bboxes = torch.tensor(redefined_bboxes, dtype=torch.float)</pre><h3><strong>Setp 2. Define distance calculation function</strong></h3><p>As a distance calculation between bounding boxes use IOU(Intersection over Union)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFg_Qxtn-F869q5UyUAXXQ.png" /><figcaption><a href="https://blog.csdn.net/weixin_42432468/article/details/85037016">Intersection over union</a></figcaption></figure><pre>def IoU(clusters: torch.tensor, bboxes: torch.tensor):<br>    iou_values = box_iou(clusters, bboxes)<br>    return iou_values</pre><h3>Step 3. Implement K-Means alghorithm</h3><blockquote>Principle of k-means:</blockquote><blockquote>The K-means algorithm is a typical distance-based clustering algorithm. The distance is used as the evaluation index of similarity. The closer the distance between two objects is, the greater the similarity. The algorithm considers clusters to be composed of objects that are close together, thus making compact and independent clusters the ultimate goal.</blockquote><pre>def KMeans(bboxes:torch.tensor, k:int, dist=torch.mean, stop_iter=5):<br>    rows = bboxes.shape[0]<br>    distances = torch.empty((rows, k))<br>    last_clusters = torch.zeros((rows, ))<br><br>    cluster_indxs = np.random.choice(rows, k, replace=False) # choose unique indexs in rows<br>    clusters = bboxes[cluster_indxs].clone()<br><br>    iteration = 0<br>    while True:<br>        # calculate the distances <br>        distances = IoU(bboxes, clusters)<br><br>        nearest_clusters = torch.argmax(distances, dim=1) # 0, 1, 2 ... K   <br><br>        if (last_clusters == nearest_clusters).all(): # break if nothing changes<br>            iteration += 1<br>            if iteration == stop_iter:<br>                break<br>        else:<br>            iteration = 0<br>        # Take the mean and step for cluster coordiantes <br>        for cluster in range(k):<br>            clusters[cluster] = torch.mean(bboxes[nearest_clusters == cluster], axis=0)<br><br>        last_clusters = nearest_clusters.clone()<br>    return clusters, distances</pre><h3>Step 4. Train and Evaluate the results</h3><p>Evaluate by using elbow method to choose optimal number of anchor boxes. Ideally if IoU more than 60% then you can specify the number of anchors.</p><pre>clusterList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]<br>mean_distances, anchorBoxes = [], []<br><br>for cluster_k in clusterList:<br>    anchors, distances = KMeans(redefined_bboxes, k=cluster_k)<br>    indxs = torch.argmax(distances, dim=1)<br>    filtered_distances = []<br>    for i, distance in enumerate(distances):<br>        filtered_distances.append(distance[indxs[i]].item())<br>    mean_distances.append(np.mean(filtered_distances))<br>    anchorBoxes.append(anchors)<br>    <br>plt.plot(clusterList, mean_distances)<br>plt.scatter(clusterList, mean_distances)<br>plt.title(&quot;Mean IoU Score&quot;)<br>plt.xlabel(&quot;Number of clusters&quot;)<br>plt.ylabel(&quot;IoU score&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*myTvgw8YotBPXMMp9m5A2g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f11c690b82" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>