<?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 Achyut Paudel on Medium]]></title>
        <description><![CDATA[Stories by Achyut Paudel on Medium]]></description>
        <link>https://medium.com/@achyutpaudel50?source=rss-a3e84c368a3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7ChNw1XfWZLjf7ve</url>
            <title>Stories by Achyut Paudel on Medium</title>
            <link>https://medium.com/@achyutpaudel50?source=rss-a3e84c368a3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:43:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@achyutpaudel50/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[YoloV8 train and inference — Detection or Segmentation on Custom Data using Roboflow]]></title>
            <link>https://medium.com/@achyutpaudel50/yolov8-train-and-inference-detection-or-segmentation-on-custom-data-using-roboflow-481c8d27445d?source=rss-a3e84c368a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/481c8d27445d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[custom-dataset]]></category>
            <category><![CDATA[instance-segmentation]]></category>
            <category><![CDATA[obejct-detection]]></category>
            <category><![CDATA[yolov8]]></category>
            <dc:creator><![CDATA[Achyut Paudel]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 08:10:41 GMT</pubDate>
            <atom:updated>2024-07-25T19:52:07.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>YoloV8 train and inference — Detection or Segmentation on Custom Data using Roboflow</h3><p>Hey guys, in this short tutorial, I am going to show how to train a custom model in Yolov8. You can use the same workflow for any basic model training and deployment, just choose different models as needed. In this tutorial, I am going to use a tool called <a href="https://roboflow.com/">roboflow</a>, which is a widely used tool for annotation and model training. We are however going to use roboflow just for annotation. I am going to show the workflow in steps. So please follow me:</p><ol><li><strong>First and foremost, install yolo v8 in your python environment ( I prefer </strong><a href="https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#activating-an-environment"><strong>anaconda</strong></a><strong> for environment management)</strong></li></ol><pre>pip install ultralytics</pre><p>It should pretty much install everything it needs by itself. Make sure your computer has all the requirements like the correct cuda versions, otherwise it wont install the whole thing. If it doesn’t install directly, install the dependencies first and do pip install ultralytics at last.</p><p>list of dependencies in link below inside <a href="https://github.com/ultralytics/ultralytics/blob/main/requirements.txt">requirements.txt</a>. You can also install from source instead of doing pip install by cloning the repository below and running <a href="https://github.com/ultralytics/ultralytics/blob/main/setup.py">setup.py</a></p><p><a href="https://github.com/ultralytics/ultralytics">GitHub - ultralytics/ultralytics: Ultralytics YOLO 🚀</a></p><p><strong>2. Data Preparation:</strong></p><p>a. Go to <a href="http://roboflow.com/">roboflow.com</a>, create account and workspace.</p><p>b. Click on Create a new project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*rQtEeLjQUfUSSH7tn-cNdQ.png" /><figcaption>Roboflow screenshot</figcaption></figure><p>c. Choose the project as required. Detection if you need a bounding box detection in image, Classification if you want to classify the image — single label per image, and Segmentation if you want a precise mask around the detected object.</p><p>d. Upload all image — choose folder or file to upload. This should upload all images. If you have pre-labelled image, you can upload the images with labels, and roboflow will do the matching. This is handy, if you already have a labelled dataset in some other format, or want to add more images to the dataset.</p><p>e. Choose dataset split — usually 70–20–10 is the best option or the one most use.</p><p>f. Now, the main part. Assign images and annotate. You can invite others to join in the annotation, or can start annotating all the images. Listen to songs, podcast, reflect on your life, talk to someone or do anything while you annotate. Make sure you annotate correctly or this would confuse the model later on. Make sure the class names are consistent throughout the images. Usually it populates class names that you have given by itself, so no need to type in everytime.</p><p>g. Generate the dataset — after this you can add preprocessing step, and augmentation step if you need to your data. You can use these steps as you need as they depend completely on the use case. You can either download the data as zip, or use the download code and run it in python. You can choose which format to download the annotations in. There is a option which says Yolov8 COCO, choose that one. There are different annotation methods — COCO is one of the commonly used one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*khmEEcWTEeL0rJLf0fQBnw.png" /><figcaption>roboflow snippet — export dataset</figcaption></figure><p>h. Download the Data: Run the script. It downloads the data in your working directory. Inside the folder will be folders <strong><em>train, test, valid</em></strong> and the config file <strong><em>data.yaml .</em></strong></p><p>3. <strong>Prepare dataset for training in yolov8 format</strong></p><ul><li>Make sure that the settings.yaml file for yolo has the datasets_dir correctly set up. datasets_dir is where yolo would search for the dataset and the config file. You can edit the <em>settings.yaml</em> for yolo using the command below and the picture below shows what it looks like. Make sure <em>datsets_dir </em>is pointing correctly at the location where your dataset is.</li></ul><pre>gedit .config/Ultralytics/settings.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X56upbd91SlWpAy_gsJOIg.png" /></figure><ul><li>Make sure your data.yaml file is correct. Make sure your path of dataset, train and test labels are set up correctly. This is what it should look like, or depending on how you set it up, make sure it is correctly set up.</li></ul><pre>names:<br>- trunks<br>nc: 1<br>test: test/images<br>train: train/images<br>val: valid/images</pre><p><strong>3. Model Training</strong></p><p>a. You can use any model YOLO provides (yolov8n, yolov8x or any pretrained yolo model you have — need to give the path to .pt file for the model) complete list of available models and other details in this <a href="https://github.com/ultralytics/ultralytics">link</a>. The snipshot below shows different models available for detection. You can click on dropdown of other tasks to see the available models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ZLpgf19717xoFKmvmGFJtQ.png" /></figure><p>b. For training the model, there are different hyperparameters that can be tuned, it is application specific. For complete list of hyperparameters and more information, go to site below:</p><p><a href="https://docs.ultralytics.com/modes/train/">Train</a></p><p>Below is the code to actually train the model. This is a simple example, and you can change and experiment with the hyperparameters to see what they do and how they affect the performance of your model.</p><pre>from ultralytics import YOLO<br>model = YOLO(&quot;yolov8n.pt&quot;)<br>data_yaml_path =&#39;Tree-Trunks-2/data.yaml&#39;<br>model.train(data = data_yaml_path,<br>            epochs=500,<br>            imgsz=640,<br>            device=0,<br>           )<br></pre><p>This saves the model inside runs folder. Usually creates a new folder everytime you set it up. To resume from previous trained model, you can set resume = True</p><p><strong>4. Running the Inference</strong></p><p>After your model is trained, it should by default save the model in runs/detect/train{}, {} maybe any number depending on how many times you have tried this. or it could be inside runs/segment/train{} depending on if you used detection or segmentation models. There could be other folder for other tasks too. Inside this folder is where your tained model is going to be along with all the validation inferences, and the model performance metrics. This is what you will report when you say your model performed good or bad.</p><p>To run the inference of the model on image, you can use the following code:</p><pre>import os<br>import cv2<br>import random<br><br>model = YOLO(&#39;runs/detect/train/weights/best.pt&#39;)<br><br>path = &#39;/home/achyut/Dataset/&#39;<br>imgp = path+&#39;/images/&#39;<br>num_images = 10<br>images = random.sample(os.listdir(imgp), num_images)<br># # Show the results<br>for image in images:<br>     imgpath = imgp+image<br>     results = model(imgpath, conf = 0.5, iou = 0.6)<br>     r = results[0]<br>     im_array = r.plot()  # plot a BGR numpy array of predictions<br>     # cv2.imwrite(&#39;predicted.png&#39;,im_array)<br>     cv2.namedWindow(&quot;asd&quot;, cv2.WINDOW_NORMAL)  <br>     cv2.imshow(&#39;asd&#39;,im_array)<br>     cv2.waitKey(0)<br>     cv2.destroyAllWindows()</pre><p>This block of code takes the trained model — <em>best.pt</em>, that is where it saves the best model while training. I am giving it a <em>path</em> to where my images are, and running the inference on randomly chosen 10 images to get an idea of how the model is performing.</p><p>So this is basically it! You can just give anyone this <em>.pt</em> file and they should be able to run the model on their machine.</p><p>I tried to be as descriptive as I could on this tutorial. Please let me know if you have any more questions, and I would be happy to help. You can contact me here:</p><p><a href="http://achyutpaudel.com/">http://achyutpaudel.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=481c8d27445d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperspectral Image Processing In Python- Custom ROI selection with mouse]]></title>
            <link>https://medium.com/@achyutpaudel50/hyperspectral-image-processing-in-python-custom-roi-selection-with-mouse-78fbaf7520aa?source=rss-a3e84c368a3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/78fbaf7520aa</guid>
            <category><![CDATA[machine-vision]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[hyperspectral-imaging]]></category>
            <category><![CDATA[hyperspectral]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Achyut Paudel]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 09:26:38 GMT</pubDate>
            <atom:updated>2024-08-15T21:17:35.388Z</atom:updated>
            <content:encoded><![CDATA[<p>Hyperspectral images are just like RGB image but huge! They have a lot of bands (channels) 200 bands or even more, and its a challenging task to process or understand anything from the data. Most of the time, you end up using the programs from the camera manufacturer. With this python program, you wont have to rely on their laggy program for ROI selection. In this tutorial, I will demostrate a custom program for interactively selecting ROI in a hyperspectral image, and saving the data.</p><p>Lets start with importing all the necessary libraries:</p><pre>from spectral import imshow, get_rgb<br>import spectral.io.envi as envi<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import matplotlib<br>import cv2<br>import os<br>import pandas as pd</pre><p>If you dont have these libraries installed already, you can do <em>pip install spectral. </em><a href="https://anaconda.org/conda-forge/spectral">spectral</a> is a library for handling hyperspectral data.</p><h3>Read the hyperspectral image</h3><p>The hyperspectral image needs three different images to get a corrected image — <em>raw data</em> (raw reflectance values from the camera),<strong><em> white_ref</em></strong>- which is the reflectance from white calibration surface, and <strong><em>dark_ref</em></strong> - the refelctance from dark (usually zeros). The white and dark references are used to calibrate and normalise the raw refelctance values using the equation: Corrected Image = {RawReflectance - DarkReflectance}/ {WhiteReflectance - DarkReflectance}</p><pre>dark_ref = envi.open(&#39;path_to_dark_ref.hdr&#39;,&#39;path_to_dark_ref&#39;)<br>white_ref = envi.open(&#39;path_to_white_ref.hdr&#39;,&#39;path_to_white_ref&#39;)<br>raw_ref = envi.open(&#39;path_to_raw.hdr&#39;,&#39;path_to_raw)</pre><pre>bands = data_ref.bands.centers<br>white_data = np.array(white_ref.load())<br>dark_data = np.array(dark_ref.load())<br>raw_data = np.array(data_ref.load())</pre><h3>Normalised (corrected) image</h3><pre>corrected_data = np.divide(<br>            np.subtract(raw_data, dark_data),<br>            np.subtract(white_data, dark_data))</pre><h3><strong>View the Image</strong></h3><p>To view the image, we can either select a band or select multiple bands to create a RGB image (select 1 band each from appropriate wavelength in Red, Green, and Blue spectrum and arrange accordingly). To get a more represntative RGB image, you can average multiple bands in each Red, Green and Blue spcetrums to get an averaged RGB image.</p><pre>#Get RGB Image<br>img = get_rgb(corrected_data, bands=None)<br><br>#Select single band<br>#sel = 70<br>#img = data_ref[:,:,sel]<br><br>image = cv2.normalize(img, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)<br>image = image.astype(np.uint8)<br>image = cv2.rotate(image,cv2.ROTATE_90_CLOCKWISE)<br><br>#Uncomment to view the RGB Image<br>#cv2.namedWindow(&quot;main&quot;, cv2.WINDOW_NORMAL)<br>#cv2.imshow(&#39;main&#39;, image)<br>#cv2.waitKey(0)<br>#cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V7Ftopoj3BMegwm_" /><figcaption>RGB Image visualization</figcaption></figure><h3><strong>Important Functions</strong></h3><ol><li>Get Right-click event</li></ol><p>This part defines a <em>mouse_callback</em> function which listens when you press-right click on your mouse. Basicallly, it stores the x,y location of the pixels you clicked on. I am rotating the image during visualization. You can comment that part, if your image is already in correct orientation.</p><pre>    #the [x, y] for each right-click event will be stored here<br>    right_clicks =[]<br>    #this function will be called whenever the mouse is right-clicked<br>    def mouse_callback(event, x, y, flags, params):<br>    <br>        #right-click event value is 2<br>        if event == 2:<br>            global right_clicks<br>    <br>            #store the coordinates of the right-click event<br>            right_clicks.append([x, y])<br>    <br>    ##Display the image for clicking<br>    cv2.namedWindow(&quot;Select the regions&quot;, cv2.WINDOW_NORMAL)<br>    #set mouse callback function for window<br>    cv2.setMouseCallback(&#39;Select the regions&#39;, mouse_callback)<br>    image = cv2.rotate(image,cv2.ROTATE_90_CLOCKWISE)<br>    cv2.imshow(&#39;Select the regions&#39;, image)<br>    cv2.waitKey(0)<br>    cv2.destroyAllWindows()</pre><p>2. Extracting the ROI from clicked point</p><p>This function now takes the l<em>ist right_click, </em>which has the x,y postions of the pixels we clicked on. Inputs to this function are: <em>array — </em>array of your data from which you have to extract the ROI, x,y are (x,y) pixel location of clicked point, (w,h) are the width and height of the ROI, intensity and line are intensities and width of the bounding box lines. The bounding box starts at the top-left corner of your clicked point, so keep that in mind.</p><pre>def extract_roi(arr, x, y, w, h, intensity, line):<br>    roi = arr[y:y+h, x:x+w, :]<br>    bounding_box = arr<br>    #THIS PART IS JUST COLORING THE BOX AROUND THE IMAGE<br>    bounding_box[y-line:y, x-line:x+w+line, :] = intensity <br>    bounding_box[y:y+h, x-line:x, :] = intensity <br>    bounding_box[y+h:y+h+line, x-line:x+w+line, :] = intensity <br>    bounding_box[y:y+h, x+w:x+w+line, :] = intensity <br><br>    return (roi, bounding_box)</pre><h3><strong><em>Get ROIs from all the clicked points.</em></strong></h3><p>This part now takes all your clicked locations — <em>right_clicks — </em>and extracts the ROI’s from that point. The <em>for </em>loop runs through all the clicked points, and saves the data in the list <em>rois</em>, which we will use later.</p><pre>    coordinates = right_clicks<br>    rois = [] # returned ROIs<br>    length = 1 # width and height<br>    intensity = 1 # bounding box line intensity<br>    line = 1 # bounding box line width<br>    bounding_boxed = corrected_nparr<br>    cd = []<br>    for coordinate in coordinates:<br>        (x, y) = coordinate<br>        x1 = y<br>        y1 = image.shape[1]-x<br>        (roi, bounding_boxed) = extract_roi(<br>            bounding_boxed, x1, y1, length, length, intensity, line)<br>        rois.append(roi)</pre><p>Here is the visualization of the clicked points. The boxes 1,2,3and4 are where I clicked and the boxes are the region of my ROIs from which I will be getting the data on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0amKLbzfePuglncP" /></figure><h3><strong>Get the average reflectance of all pixels in the ROI.</strong></h3><p>This code snippet now gets the reflectance from all pixels across your ROIs. From each ROI, you will be getting one average reflectance value. <em>int_m_1 </em>is your final average reflectance for all your ROI’s. If you selected 10 ROIs and your hyperspectral image has 274 bands, <em>int_m_1 </em>will be of size (10,274). Just make sure.</p><pre>int_m = []<br>for i in range(len(rois)):<br>    roi = rois[i]<br>    intensity = []<br>    for b in range(roi.shape[2]):<br>        intensity.append(np.mean(roi[:, :, b]))<br>    int_m.append(intensity)<br>    int_m_1 = np.array(int_m)<br>    int_m_1 = np.mean(int_m,axis=0)</pre><p>Now plot the average reflectances across your ROI to visualize and obvious pattern from your data.</p><pre>plt.figure(3)<br>plt.plot(bands, int_m_1, label=&#39;Mean Reflectance&#39;)<br><br><br>plt.legend(loc=&#39;upper left&#39;)<br>plt.title(&#39;Leaf Spectral Footprint\\n Mean in ROI Area&#39;)<br>plt.xlabel(&#39;Wavelength (nm)&#39;)<br>plt.ylabel(&#39;Reflectance&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GKjOv7FK3SFQfjod" /></figure><p>Show the final image with ROIs</p><pre>cv2.namedWindow(&quot;main&quot;, cv2.WINDOW_NORMAL)<br>image_sel = corrected_nparr[:,:,70]<br>image_sel = cv2.rotate(image_sel,cv2.cv2.ROTATE_90_CLOCKWISE)<br>cv2.imshow(&#39;main&#39;, image_sel)<br>cv2.waitKey(0)</pre><p>You can visualize this data everytime or you can run this whole code in a loop for all your data, and save the average reflectances with the labels, to get a curated dataset, on which you can run different machine learning algortihms on.</p><h3><strong>Next Steps</strong></h3><p>After processing the data and getting the average reflectances values for each sample, we need to apply some machine learning models like SVM, Decision Trees, Boosting or any other techniques to perform the regression or classification task as required.</p><p>If you found this helpful, please cite our work, where we used the same method for data processing.</p><p><a href="https://www.sciencedirect.com/science/article/pii/S016816992300563X?casa_token=-qNvXN2G9_8AAAAA:qNkOIHfH7UJYqPk1Xwg0-kedgYUITJ_kYdGxjvL3QwhHJWwxo5o47fcBVmoJ3-0PdqkRPBPeMGRG"><em>Kang, C., Diverres, G., Achyut, P., Karkee, M., Zhang, Q., &amp; Keller, M. (2023). Estimating soil and grapevine water status using ground based hyperspectral imaging under diffused lighting conditions: Addressing the effect of lighting variability in vineyards. Computers and Electronics in Agriculture, 212, 108175.</em></a></p><p>Thanks for folowing! Let me know if you need more techniques on hyperspectral Image Processing, or if you have any questions in general.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78fbaf7520aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>