<?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 ShioDev on Medium]]></title>
        <description><![CDATA[Stories by ShioDev on Medium]]></description>
        <link>https://medium.com/@shiodev?source=rss-f85efe070a02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ib8CXWQHSBcilBNkIblf5A.png</url>
            <title>Stories by ShioDev on Medium</title>
            <link>https://medium.com/@shiodev?source=rss-f85efe070a02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:08:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shiodev/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[Detecting Green Cells in Grid Squares: A Step-by-Step Guide with OpenCV and Python (Part 4)]]></title>
            <link>https://medium.com/@shiodev/detecting-green-cells-in-grid-squares-a-step-by-step-guide-with-opencv-and-python-end-c7c75714219f?source=rss-f85efe070a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7c75714219f</guid>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[plant-cell]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[ShioDev]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 15:21:59 GMT</pubDate>
            <atom:updated>2025-04-01T08:26:42.745Z</atom:updated>
            <content:encoded><![CDATA[<p>In this continuation from part 3, I’ll be fine-tuning and improving the square cropping process in our image processing project. Here are the three new features I will be updating in this post:</p><ol><li><strong>Improved Margin Adjustment for Cropped Squares</strong></li><li><strong>Enhanced Filtering of Green Cells</strong></li><li><strong>Batch Processing of Multiple Images</strong></li><li><strong>Improved Margin Adjustment for Cropped Squares</strong></li></ol><p>~~~</p><p>Previous post:</p><p>Part 1: <a href="https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c">https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c</a></p><p>Part 2: <a href="https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-2-31408b5671a6">https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-2-31408b5671a6</a></p><p>Part 3: <a href="https://medium.com/@shiodev/detecting-green-cells-in-grid-squares-a-step-by-step-guide-with-opencv-and-python-part-3-9a22979846d4">https://medium.com/@shiodev/detecting-green-cells-in-grid-squares-a-step-by-step-guide-with-opencv-and-python-part-3-9a22979846d4</a></p><p>I also build a Github Repository at:<br><a href="https://github.com/katanukisatoshi/cells-detector">https://github.com/shiofreces/cells-detector</a></p><p>~~~</p><h3>Step 1: Find Intersections</h3><p>Now, we need to find intersections between the horizontal and vertical lines. These intersections will help us identify the corners of potential squares. This is the big change from the 1st post.</p><pre>def find_intersections(horizontal_lines, vertical_lines):<br>    intersections = []<br>    for y in horizontal_lines:<br>        for x in vertical_lines:<br>            intersections.append((x, y))<br>    return intersections</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*2ugHNEFhnvNx7s0bkM9t6w.png" /></figure><p>The intersections of the horizontal and vertical lines have been marked with red circles on the image. These intersections help in identifying and labeling the squares within the grid.</p><h3>Step 2: Identify and Label Squares</h3><p>Using the intersections, we can identify squares within the image. We check each potential square to ensure it meets the aspect ratio and area criteria, and then we label them.</p><pre>def identify_and_label_squares(image, intersections, horizontal_lines, vertical_lines, aspect_ratio_tolerance=0.2, min_area=500):<br>    intersections = sorted(intersections, key=lambda pt: (pt[1], pt[0]))<br>    squares = []<br>    index = 1<br><br>    for i in range(len(horizontal_lines) - 1):<br>        for j in range(len(vertical_lines) - 1):<br>            top_left = (vertical_lines[j], horizontal_lines[i])<br>            top_right = (vertical_lines[j+1], horizontal_lines[i])<br>            bottom_left = (vertical_lines[j], horizontal_lines[i+1])<br>            bottom_right = (vertical_lines[j+1], horizontal_lines[i+1])<br><br>            if top_left in intersections and top_right in intersections and bottom_left in intersections and bottom_right in intersections:<br>                width = vertical_lines[j+1] - vertical_lines[j]<br>                height = horizontal_lines[i+1] - horizontal_lines[i]<br>                area = width * height<br>                aspect_ratio = float(width) / height<br><br>                if 1 - aspect_ratio_tolerance &lt;= aspect_ratio &lt;= 1 + aspect_ratio_tolerance and area &gt;= min_area:<br>                    pts = np.array([top_left, top_right, bottom_right, bottom_left])<br>                    squares.append((pts, (vertical_lines[j], horizontal_lines[i], width, height)))<br>                    cv2.polylines(image, [pts], isClosed=True, color=(255, 0, 0), thickness=2)<br>                    center_x = (top_left[0] + bottom_right[0]) // 2<br>                    center_y = (top_left[1] + bottom_right[1]) // 2<br>                    cv2.putText(image, str(index), (center_x, center_y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)<br>                    index += 1<br><br>    return image, squares</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*nOKgqZi0o-JZnCSEHmHPng.png" /></figure><p>The image has been processed to identify and label the squares. Each square is outlined in blue, and the squares are numbered from 1 to 16. The intersections of the lines have been used to delineate these squares accurately. We can adjust <em>“aspect_ratio_tolerance” </em>and <em>“min_area”</em> for testing.</p><h3>Step 3: Show Cropped Squares &amp; Detect Green Cells</h3><p>Finally, we display the cropped squares along with the detected green cells. This visualization helps in analyzing the content of each square.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RY61a_NNWog74C0WdwmZAA.png" /><figcaption>Cropped Squares &amp; Detect Green Cells with <strong><em>margin</em></strong> = 5</figcaption></figure><p>The image processing script successfully identified and labeled the squares, detected green cells within each square, and displayed the results. Each subplot shows a cropped square with detected green cells highlighted and their respective areas displayed.</p><p>Enjoy Coding!</p><p>Shio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c75714219f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Green Cells in Grid Squares: A Step-by-Step Guide with OpenCV and Python (Part 3)]]></title>
            <link>https://medium.com/@shiodev/detecting-green-cells-in-grid-squares-a-step-by-step-guide-with-opencv-and-python-part-3-9a22979846d4?source=rss-f85efe070a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a22979846d4</guid>
            <category><![CDATA[cell-detector]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[opencv-python]]></category>
            <dc:creator><![CDATA[ShioDev]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 09:14:17 GMT</pubDate>
            <atom:updated>2025-04-01T08:28:25.827Z</atom:updated>
            <content:encoded><![CDATA[<p>After completing Parts 1 and 2, I realized that enhancing the input quality could significantly improve the results. Better input leads to better results.</p><p>Previous post:</p><p>Part 1: <a href="https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c">https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c</a></p><p>Part 2: <a href="https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-2-31408b5671a6">https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-2-31408b5671a6</a></p><p>I also build a Github Repository at:<br><a href="https://github.com/shiofreecss/cells-detector">https://github.com/shiofreecss/cells-detector</a></p><p>~~</p><p>To reduce redundancy, lines that are close to each other are merged. By adjusting the merge threshold from 50 to 20, the approach ensures that only significantly spaced lines are merged, improving the accuracy of the final line detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x3YGooJHBJp3gZRi" /><figcaption>After I changed the merging threshold from 50–20</figcaption></figure><pre>def merge_nearest_lines(lines, image, threshold=20): #Change to 20-25 for testing<br>    horizontal_lines = []<br>    vertical_lines = []</pre><h3>Step 1: Filtering Lines with Large Gaps</h3><p>Lines with gaps exceeding specified thresholds are filtered out. This step ensures that only closely spaced lines are retained, improving the accuracy of line detection.</p><h4><strong>a — Top and Bottom Lines</strong></h4><p>For the top and bottom lines, gaps are evaluated, and lines with gaps exceeding the thresholds of 30 and 40 respectively are removed.</p><p><strong><em>1 — Top Lines</em></strong></p><pre>def remove_lines_with_large_gap_top(horizontal_lines, gap_threshold=30):<br>    top_lines = horizontal_lines[:6]<br>    filtered_top_lines = [top_lines[0]]<br>    for i in range(1, len(top_lines)):<br>        if (top_lines[i] - top_lines[i-1]) &lt;= gap_threshold:<br>            filtered_top_lines.append(top_lines[i])<br>    return filtered_top_lines<br><br>def change_color_of_filtered_top_lines(image_with_merged_lines, filtered_top_lines, color=(255, 0, 0), line_thickness=2):<br>    modified_image = np.copy(image_with_merged_lines)<br>    for y in filtered_top_lines:<br>        cv2.line(modified_image, (0, y), (modified_image.shape[1], y), color, line_thickness)<br>    return modified_image<br><br>filtered_top_lines = remove_lines_with_large_gap_top(merged_horizontal_lines, gap_threshold=30)<br>image_with_filtered_top_lines = change_color_of_filtered_top_lines(image_with_merged_lines, filtered_top_lines)</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mLLPB_7icajU4DVT" /><figcaption>Top Lines Colored with Gap Threshold 30</figcaption></figure><p><strong><em>2 — Bottom Lines</em></strong></p><pre>def remove_lines_with_large_gap_bottom(horizontal_lines, gap_threshold=30):<br>    bottom_lines = horizontal_lines[-5:]<br>    filtered_bottom_lines = []<br>    for i in range(len(bottom_lines) - 1):<br>        if (bottom_lines[i+1] - bottom_lines[i]) &lt;= gap_threshold:<br>            filtered_bottom_lines.append(bottom_lines[i])<br>            filtered_bottom_lines.append(bottom_lines[i+1])<br>    filtered_bottom_lines = list(set(filtered_bottom_lines))  # Remove duplicates<br>    filtered_bottom_lines.sort()  # Ensure the lines are sorted<br>    return filtered_bottom_lines<br><br>def change_color_of_filtered_bottom_lines(image_with_merged_lines, filtered_bottom_lines, color=(255, 0, 0), line_thickness=2):<br>    modified_image = np.copy(image_with_merged_lines)<br>    for y in filtered_bottom_lines:<br>        cv2.line(modified_image, (0, y), (modified_image.shape[1], y), color, line_thickness)<br>    return modified_image<br><br>filtered_bottom_lines = remove_lines_with_large_gap_bottom(merged_horizontal_lines, gap_threshold=30)<br>image_with_filtered_bottom_lines = change_color_of_filtered_bottom_lines(image_with_filtered_top_lines, filtered_bottom_lines)</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eZy9EZD0LHhoDQtW" /><figcaption>Bottom Lines Colored with Gap Threshold 30</figcaption></figure><h4><strong>b — Left and Right Lines</strong></h4><p>For the left and right lines, gaps are evaluated, and lines with gaps exceeding the threshold of 30 are removed.</p><p><strong><em>1 — Right Lines</em></strong></p><pre>def remove_lines_with_large_gap_right(vertical_lines, gap_threshold=30):<br>    right_lines = vertical_lines[-6:]<br>    filtered_right_lines = []<br>    for i in range(len(right_lines) - 1):<br>        if (right_lines[i+1] - right_lines[i]) &lt;= gap_threshold:<br>            filtered_right_lines.append(right_lines[i])<br>            filtered_right_lines.append(right_lines[i+1])<br>    filtered_right_lines = list(set(filtered_right_lines))  # Remove duplicates<br>    filtered_right_lines.sort()  # Ensure the lines are sorted<br>    return filtered_right_lines<br><br>def change_color_of_filtered_right_lines(image_with_merged_lines, filtered_right_lines, color=(255, 0, 0), line_thickness=2):<br>    modified_image = np.copy(image_with_merged_lines)<br>    for x in filtered_right_lines:<br>        cv2.line(modified_image, (x, 0), (x, modified_image.shape[0]), color, line_thickness)<br>    return modified_image<br><br>filtered_right_lines = remove_lines_with_large_gap_right(merged_vertical_lines, gap_threshold=30)<br>image_with_filtered_right_lines = change_color_of_filtered_right_lines(image_with_filtered_bottom_lines, filtered_right_lines)</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6NTEPQFLXbzhl9z" /><figcaption>Right Lines Colored with Gap Threshold 30</figcaption></figure><p><strong><em>Left Lines</em></strong></p><pre>def remove_lines_with_large_gap_left(vertical_lines, gap_threshold=30):<br>    left_lines = vertical_lines[:6]<br>    filtered_left_lines = []<br>    for i in range(len(left_lines) - 1):<br>        if (left_lines[i+1] - left_lines[i]) &lt;= gap_threshold:<br>            filtered_left_lines.append(left_lines[i])<br>            filtered_left_lines.append(left_lines[i+1])<br>    filtered_left_lines = list(set(filtered_left_lines))  # Remove duplicates<br>    filtered_left_lines.sort()  # Ensure the lines are sorted<br>    return filtered_left_lines<br><br>def change_color_of_filtered_left_lines(image_with_merged_lines, filtered_left_lines, color=(255, 0, 0), line_thickness=2):<br>    modified_image = np.copy(image_with_merged_lines)<br>    for x in filtered_left_lines:<br>        cv2.line(modified_image, (x, 0), (x, modified_image.shape[0]), color, line_thickness)<br>    return modified_image<br><br>filtered_left_lines = remove_lines_with_large_gap_left(merged_vertical_lines, gap_threshold=30)<br>image_with_filtered_left_lines = change_color_of_filtered_left_lines(image_with_filtered_right_lines, filtered_left_lines)</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wl8motW4fIRZBtVL" /><figcaption>All Nearest Lines Colored with Gap Threshold 30</figcaption></figure><h3>Step 2: Change the Color of Filtered Lines</h3><p>To visually distinguish the filtered lines, change their color.</p><pre>def change_color_of_filtered_lines(image_with_merged_lines, filtered_lines, is_horizontal=True, color=(255, 0, 0), line_thickness=2):<br>    modified_image = np.copy(image_with_merged_lines)<br>    if is_horizontal:<br>        for y in filtered_lines:<br>            cv2.line(modified_image, (0, y), (modified_image.shape[1], y), color, line_thickness)<br>    else:<br>        for x in filtered_lines:<br>            cv2.line(modified_image, (x, 0), (x, modified_image.shape[0]), color, line_thickness)<br>    return modified_image</pre><h3>Step 3: Highlight the Nearest Line to the Center</h3><p>Identify and highlight the nearest line to the center from the filtered lines. I am not using AI so there is a logic should be added to this step.</p><pre># Function to find and change the color of the nearest line to the center after specific filtering steps<br>def highlight_nearest_center_line_after_filtering(image, filtered_lines, is_horizontal=True, color=(0, 0, 255), line_thickness=2):<br>    center_y = image.shape[0] // 2<br>    center_x = image.shape[1] // 2<br><br>    if is_horizontal:<br>        # Find the nearest horizontal line to the center<br>        nearest_line = min(filtered_lines, key=lambda y: abs(y - center_y))<br>        cv2.line(image, (0, nearest_line), (image.shape[1], nearest_line), color, line_thickness)<br>    else:<br>        # Find the nearest vertical line to the center<br>        nearest_line = min(filtered_lines, key=lambda x: abs(x - center_x))<br>        cv2.line(image, (nearest_line, 0), (nearest_line, image.shape[0]), color, line_thickness)<br>    <br>    return image</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPIXXO-H51VQBjRSUMGC7A.png" /><figcaption>The detected line must be the nearest center</figcaption></figure><p>Amazing! The area could be detected quite good here~</p><h3>Step 4: Cover the Area Created by the Nearest Highlighted Lines</h3><p>Finally, cover the area created by the nearest highlighted lines to create a visual marker.</p><pre># Function to cover the area created by the nearest highlighted lines<br>def cover_area_by_nearest_lines(image, nearest_top, nearest_bottom, nearest_left, nearest_right, color=(255, 0, 0), thickness=2):<br>    covered_image = np.copy(image)<br>    # Draw rectangle covering the area<br>    cv2.rectangle(covered_image, (nearest_left, nearest_top), (nearest_right, nearest_bottom), color, thickness)<br>    return covered_image</pre><p><em>Results:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saTGlujoikCjyqyGYBR4IQ.png" /></figure><p>With this result we can combine with crop function in Post 1 &amp; 2 for better result. The blue area will be cropped perfectly.</p><h3>Step 5: Crop the area created by highlighted lines</h3><pre># Function to crop the area created by the nearest highlighted lines<br>def crop_area_by_nearest_lines(image, nearest_top, nearest_bottom, nearest_left, nearest_right):<br>    cropped_image = image[nearest_top:nearest_bottom, nearest_left:nearest_right]<br>    return cropped_image<br><br># Crop the area created by those nearest highlighted lines<br>cropped_image = crop_area_by_nearest_lines(image, nearest_top_line, nearest_bottom_line, nearest_left_line, nearest_right_line)<br>display_image(cropped_image, &#39;Cropped Area by Nearest Highlighted Lines&#39;)</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v8VAIVK4Q0EYSa3Q" /><figcaption>Cropped image</figcaption></figure><p>I want to add little bit margin to the crop image.</p><pre># Function to crop the area created by the nearest highlighted lines with an added margin<br>def crop_area_with_margin(image, nearest_top, nearest_bottom, nearest_left, nearest_right, margin=20):<br>    top = max(0, nearest_top - margin)<br>    bottom = min(image.shape[0], nearest_bottom + margin)<br>    left = max(0, nearest_left - margin)<br>    right = min(image.shape[1], nearest_right + margin)<br>    <br>    cropped_image = image[top:bottom, left:right]<br>    return cropped_image<br><br># Crop the area created by those nearest highlighted lines with an added margin of 20 pixels<br>cropped_image_with_margin = crop_area_with_margin(image, nearest_top_line, nearest_bottom_line, nearest_left_line, nearest_right_line, margin=20)<br>display_image(cropped_image_with_margin, &#39;Cropped Area with 20 Pixel Margin&#39;)</pre><p><em>Result:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfOfRh04wkJRD7jN" /></figure><p>The image has been successfully cropped with a 20-pixel margin around the nearest highlighted lines.</p><p>Hope you guys have a good day. Enjoy!</p><p>Shio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a22979846d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Green Cells in Grid Squares: A Step-by-Step Guide with OpenCV and Python (Part 2)]]></title>
            <link>https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-2-31408b5671a6?source=rss-f85efe070a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/31408b5671a6</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[plant-cell]]></category>
            <dc:creator><![CDATA[ShioDev]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 09:04:35 GMT</pubDate>
            <atom:updated>2025-04-01T08:29:40.550Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous post, I updated code with features includes:</p><ol><li><strong>Loading and converting the image to grayscale.</strong></li><li><strong>Detecting edges in the grayscale image.</strong></li><li><strong>Detecting lines using the Hough Line Transform.</strong></li><li><strong>Merging nearby lines to reduce redundancy.</strong></li><li><strong>Indexing each square in the image.</strong></li></ol><p>Previous post: <a href="https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c">https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c</a></p><p>In this post, I will create a function to crop each square into multiple images. This will be useful for the subsequent procedure of counting the number of plant cells in each square area.</p><h3>Step 6: Index and Crop the Squares (Updated)</h3><p>Finally, we index each square in the image, crop them, and save the cropped squares as separate images.</p><pre>def index_and_crop_squares(image, horizontal_lines, vertical_lines):<br>    index = 1<br>    horizontal_lines_excluding_top = horizontal_lines[1:]<br>    cropped_squares = []<br><br>    for i in range(len(horizontal_lines_excluding_top) - 1):<br>        for j in range(len(vertical_lines) - 1):<br>            top_left = (vertical_lines[j], horizontal_lines_excluding_top[i])<br>            bottom_right = (vertical_lines[j + 1], horizontal_lines_excluding_top[i + 1])<br>            # Crop the square<br>            cropped_square = image[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]<br>            cropped_squares.append((index, cropped_square))<br>            index += 1<br>    return cropped_squares<br><br>def process_image_and_save_squares(image_path, num_squares=5):<br>    image, gray_image = load_and_convert_image(image_path)<br>    edges = detect_edges(gray_image)<br>    lines = detect_lines(edges)<br>    _, merged_horizontal_lines, merged_vertical_lines = merge_nearest_lines(lines, image)<br>    cropped_squares = index_and_crop_squares(image, merged_horizontal_lines, merged_vertical_lines)<br>    <br>    saved_squares = []<br>    for i in range(min(num_squares, len(cropped_squares))):<br>        square_index, square_image = cropped_squares[i]<br>        square_path = f&#39;./processing_data/square_{square_index}.jpg&#39;<br>        cv2.imwrite(square_path, square_image)<br>        saved_squares.append(square_path)<br>    <br>    return saved_squares<br><br># Usage example<br>image_path = &#39;path_to_your_image.jpg&#39;<br>saved_square_paths = process_image_and_save_squares(image_path, num_squares=5)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*I2466--Aw3H4nK3BevEVJg.png" /><figcaption>Cropped square image</figcaption></figure><h3>Step 7: Detect Green Cells And Improve Function</h3><p>We will now add a function to detect green cells in the image.</p><p>Result from test function:</p><pre>import cv2<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Load the image<br>image_path = &#39;./processing_data/square_1.jpg&#39;<br>image = cv2.imread(image_path)<br><br># Convert the image to HSV color space<br>hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)<br><br># Define the range for green color in HSV<br>lower_green = np.array([40, 40, 40])<br>upper_green = np.array([80, 255, 255])<br><br># Create a mask for the green color<br>mask = cv2.inRange(hsv_image, lower_green, upper_green)<br><br># Find contours in the mask<br>contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)<br><br># Count the number of green cells<br>number_of_green_cells = len(contours)<br><br># Draw contours on the original image<br>output_image = image.copy()<br>cv2.drawContours(output_image, contours, -1, (0, 255, 0), 2)<br><br># Display the result<br>plt.figure(figsize=(10, 10))<br>plt.subplot(1, 2, 1)<br>plt.title(&#39;Original Image&#39;)<br>plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))<br>plt.subplot(1, 2, 2)<br>plt.title(&#39;Green Cells Counted&#39;)<br>plt.imshow(cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ziAOm4qWpH6fh1uA" /><figcaption>Do the function to detect the green cell</figcaption></figure><p>Result:</p><pre>25</pre><p>It still have a lot of noise here. So I continue adjust the HSV value again.</p><p>Green plant cells typically have a distinct green color due to chlorophyll, which can be effectively detected in the HSV color space. The HSV range for green typically falls within these ranges:</p><ul><li>Hue (H): 35 to 85</li><li>Saturation (S): 40 to 255</li><li>Value (V): 40 to 255</li></ul><pre>def detect_green_cells(image_path, min_area_threshold=100, display_result=True):<br>    # Load the image<br>    image = cv2.imread(image_path)<br><br>    # Convert the image to HSV color space<br>    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)<br><br>    # Define the HSV range for green color detection<br>    lower_green = np.array([30, 30, 30])<br>    upper_green = np.array([90, 255, 255])<br><br>    # Create a mask for the green color<br>    mask_green = cv2.inRange(hsv_image, lower_green, upper_green)<br><br>    # Apply morphological transformations to remove noise and better define the cell boundaries<br>    kernel = np.ones((3, 3), np.uint8)<br>    mask_green_morphed = cv2.morphologyEx(mask_green, cv2.MORPH_CLOSE, kernel)<br>    mask_green_morphed = cv2.morphologyEx(mask_green_morphed, cv2.MORPH_OPEN, kernel)<br><br>    # Find contours in the morphed mask<br>    contours, _ = cv2.findContours(mask_green_morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)<br><br>    # Filter contours by area<br>    filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) &gt; min_area_threshold]<br><br>    # Draw filtered contours and bounding boxes on the original image<br>    output_image = image.copy()<br>    for cnt in filtered_contours:<br>        x, y, w, h = cv2.boundingRect(cnt)<br>        cv2.drawContours(output_image, [cnt], -1, (0, 255, 0), 2)<br>        cv2.rectangle(output_image, (x, y), (x + w, y + h), (255, 0, 0), 2)<br>        area = cv2.contourArea(cnt)<br>        cv2.putText(output_image, f&#39;Area: {area}&#39;, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)<br><br>    # Display the result if requested<br>    if display_result:<br>        plt.figure(figsize=(10, 10))<br>        plt.title(&#39;Green Cells Detection&#39;)<br>        plt.imshow(cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB))<br>        plt.show()<br><br>    # Return the number of detected cells and the output image with annotations<br>    return len(filtered_contours), output_image<br><br># Example usage<br>image_path = &#39;./processing_data/square_1.jpg&#39;<br>num_cells, annotated_image = detect_green_cells(image_path)<br>print(f&quot;Number of green cells detected: {num_cells}&quot;)</pre><p>Test with <em>square_1.jpg</em>. The detection process for the new image identified 8 cell detected while I can see ~10–11 cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fHP7_h4D5tqmGWEq" /></figure><p>Test with <em>square_2.jpg</em>. The detection process for the new image identified 12 green cells while I can identify about 13–14 cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TB9NnXlfYfn9YGfK" /></figure><h3><strong>Summary</strong></h3><p>The presented method demonstrates a robust approach to detecting and analyzing plant cells in microscopic images using OpenCV. This technique can be further refined and adapted for other types of cells or imaging conditions. The combination of color-based segmentation and morphological processing proves effective in isolating and quantifying plant cells, aiding in various research endeavors.</p><h3><strong>Future Work</strong></h3><p>Future improvements could include:</p><ul><li>Implementing machine learning models for more adaptive color segmentation.</li><li>Enhancing image resolution and clarity to improve detection accuracy.</li><li>Applying the methodology to other cell types and imaging modalities.</li></ul><p>Enjoy!</p><p>Katanuki</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31408b5671a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Green Cells in Grid Squares: A Step-by-Step Guide with OpenCV and Python (Part 1)]]></title>
            <link>https://medium.com/@shiodev/analyzing-and-processing-grid-images-with-opencv-part-1-d5c42ab0703c?source=rss-f85efe070a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5c42ab0703c</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[plant-cell]]></category>
            <category><![CDATA[biology]]></category>
            <dc:creator><![CDATA[ShioDev]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 06:58:23 GMT</pubDate>
            <atom:updated>2025-04-01T08:27:13.675Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently came across this fascinating image shared by a friend from the Biology Department. It inspired me to delve into the realm of computer vision with OpenCV. With advancements in AI, there’s immense potential to enhance the detection capabilities of plant cells, promising more precise and insightful analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCcSNhJWUSorAaRsCaWHEw.jpeg" /><figcaption>The plan cell image, I received from my friend</figcaption></figure><p>In this article, I’ll guide you through the process of analyzing a grid image using OpenCV. I’ll break down the task into several steps and functions, making the code modular and easy to understand. Let’s get started!</p><h3>Step 1: Load and Convert the Image to Grayscale</h3><p>First, we need to load the image and convert it to grayscale. This simplifies the image processing steps that follow.</p><pre>import cv2<br>import matplotlib.pyplot as plt<br><br>def load_and_convert_image(image_path):<br>    image = cv2.imread(image_path)<br>    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>    return image, gray_image<br><br>def display_image(image, title):<br>    plt.figure(figsize=(8, 8))<br>    plt.title(title)<br>    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))<br>    plt.axis(&#39;off&#39;)<br>    plt.show()<br><br>def display_gray_image(gray_image, title):<br>    plt.figure(figsize=(8, 8))<br>    plt.title(title)<br>    plt.imshow(gray_image, cmap=&#39;gray&#39;)<br>    plt.axis(&#39;off&#39;)<br>    plt.show()<br><br># Load the image<br>image_path = &#39;path_to_your_image.jpg&#39;<br>image, gray_image = load_and_convert_image(image_path)<br>display_image(image, &#39;Original Image&#39;)<br>display_gray_image(gray_image, &#39;Grayscale Image&#39;)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9AR8glv8nD0Jiv1Q" /><figcaption>Grayscale Result</figcaption></figure><h3>Step 2: Detect Edges in the Grayscale Image</h3><p>Edge detection helps us find the boundaries of the squares in the image.</p><pre>def detect_edges(gray_image, threshold1=50, threshold2=150):<br>    edges = cv2.Canny(gray_image, threshold1, threshold2, apertureSize=3)<br>    return edges<br><br>edges = detect_edges(gray_image)<br>display_gray_image(edges, &#39;Edge Detection&#39;)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7r04eqCjGrNL9Gy0OgwBHw.png" /><figcaption>Edge Detection Result</figcaption></figure><h3>Step 3: Detect Lines Using Hough Line Transform</h3><p>I will use the Hough Line Transform to detect lines in the edge-detected image.</p><pre>def detect_lines(edges, threshold=100, min_line_length=100, max_line_gap=10):<br>    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=threshold, minLineLength=min_line_length, maxLineGap=max_line_gap)<br>    return lines<br><br>lines = detect_lines(edges)<br>if lines is not None:<br>    image_with_lines = np.copy(image)<br>    for line in lines:<br>        x1, y1, x2, y2 = line[0]<br>        cv2.line(image_with_lines, (x1, y1), (x2, y2), (0, 255, 0), 2)<br>    display_image(image_with_lines, &#39;Detected Lines&#39;)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHUPqlgoVgUWuz4yIrzrPg.png" /><figcaption>Detected Lines Result</figcaption></figure><h3>Step 4: Merge Nearest Lines</h3><p>The results from step 3 appear too complex due to the numerous detected lines. To simplify and enhance the detection process, we merge nearby lines. This improves accuracy by consolidating lines that are close to each other.</p><pre>import numpy as np<br><br>def merge_nearest_lines(lines, image, threshold=50):<br>    horizontal_lines = []<br>    vertical_lines = []<br><br>    for line in lines:<br>        x1, y1, x2, y2 = line[0]<br>        if abs(y1 - y2) &lt; 10:  # Horizontal line<br>            horizontal_lines.append(y1)<br>        elif abs(x1 - x2) &lt; 10:  # Vertical line<br>            vertical_lines.append(x1)<br><br>    horizontal_lines = sorted(set(horizontal_lines))<br>    vertical_lines = sorted(set(vertical_lines))<br><br>    def merge_lines(line_positions, threshold):<br>        merged_lines = []<br>        current_line = line_positions[0]<br><br>        for line in line_positions[1:]:<br>            if line - current_line &lt;= threshold:<br>                continue<br>            else:<br>                merged_lines.append(current_line)<br>                current_line = line<br><br>        merged_lines.append(current_line)<br>        return merged_lines<br><br>    merged_horizontal_lines = merge_lines(horizontal_lines, threshold)<br>    merged_vertical_lines = merge_lines(vertical_lines, threshold)<br><br>    image_with_merged_lines = np.copy(image)<br><br>    for y in merged_horizontal_lines:<br>        cv2.line(image_with_merged_lines, (0, y), (image.shape[1], y), (0, 255, 0), 2)<br><br>    for x in merged_vertical_lines:<br>        cv2.line(image_with_merged_lines, (x, 0), (x, image.shape[0]), (0, 255, 0), 2)<br><br>    return image_with_merged_lines, merged_horizontal_lines, merged_vertical_lines<br><br>image_with_merged_lines, merged_horizontal_lines, merged_vertical_lines = merge_nearest_lines(lines, image)<br>display_image(image_with_merged_lines, &#39;Merged Lines&#39;)</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thnkrNNkM_rqoJppIPFOXg.png" /><figcaption>Merged Lines Result</figcaption></figure><h3>Step 5: Count the Smallest Unit Squares</h3><p>Great, it looks much better now. Next, we’ll count the smallest unit squares formed by the merged lines.</p><pre>def count_unit_squares(horizontal_lines, vertical_lines):<br>    horizontal_lines_excluding_top = horizontal_lines[1:]<br>    square_count = (len(horizontal_lines_excluding_top) - 1) * (len(vertical_lines) - 1)<br>    return square_count<br><br>unit_square_count = count_unit_squares(merged_horizontal_lines, merged_vertical_lines)<br>print(f&#39;Number of smallest unit squares: {unit_square_count}&#39;)</pre><p>Output:</p><pre>Number of smallest unit squares: 28</pre><h3>Step 6: Index the Squares in the Image</h3><p>Finally, we index each square in the image and display the result.</p><pre>def index_squares(image, horizontal_lines, vertical_lines):<br>    index = 1<br>    horizontal_lines_excluding_top = horizontal_lines[1:]<br><br>    for i in range(len(horizontal_lines_excluding_top) - 1):<br>        for j in range(len(vertical_lines) - 1):<br>            top_left = (vertical_lines[j], horizontal_lines_excluding_top[i])<br>            bottom_right = (vertical_lines[j + 1], horizontal_lines_excluding_top[i + 1])<br>            # Draw the index on the image<br>            cv2.putText(image, str(index), <br>                        (top_left[0] + 5, top_left[1] + 30), <br>                        cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)<br>            index += 1<br>    return image<br><br>image_with_indexed_squares = index_squares(image_with_merged_lines, merged_horizontal_lines, merged_vertical_lines)<br>display_image(image_with_indexed_squares, &#39;Indexed Squares&#39;)</pre><p>Result: Here is the result of indexing the squares in the image. The image now displays each square with its corresponding index number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ytvr3ZgDo4pEUDIS" /><figcaption>Indexed Squares Result</figcaption></figure><h3>Summary</h3><p>This process involves several steps to analyze and process a grid image:</p><ol><li><strong>Load and Display the Original Image:</strong> The provided image is loaded and displayed.</li><li><strong>Convert to Grayscale:</strong> The image is converted to grayscale to simplify further processing.</li><li><strong>Edge Detection:</strong> Edges in the grayscale image are detected using the Canny method.</li><li><strong>Hough Line Transform:</strong> Lines in the image are detected using the Hough Line Transform.</li><li><strong>Merge Nearest Lines:</strong> Detected lines are merged to reduce redundancy and better define the grid.</li><li><strong>Count Unit Squares:</strong> The number of unit squares formed by the merged lines is counted.</li><li><strong>Index Squares:</strong> Each square is indexed and visually labeled within the image.</li></ol><p>Each step includes visualizations and debug outputs to help understand the intermediate results and transformations applied to the image. This comprehensive approach enables detailed analysis and processing of grid images using OpenCV.</p><p>Enjoy!</p><p>Shio</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5c42ab0703c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>