[Python] How to measure the length of image from a masked image using OpenCV?

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    I am new in image processing and I am trying to improve myself by doing some projects and I have a problem about my project. I have an image dataset containing lakes with their corresponding binary mask images. I want to calculate the perimeter (boundary length) and area of the lake in each image using OpenCV.

    So far, I have tried Canny Edge Detection and cv2.findContours() to detect the lake boundaries to find lake's real area and real perimeter, but I am struggling to get only the lake's contour without including unwanted edges (such as image borders or noise).

    Here is my current code:

    import cv2
    import matplotlib.pyplot as plt
    import numpy as np



    # Load the image
    image = cv2.imread("water_body_3.jpg")

    # Apply Canny edge detection
    edged = cv2.Canny(image, 50, 100)

    # Find contours
    contours, _ = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    largest_contour = max(contours, key=cv2.contourArea)

    # Draw the detected contours
    cv2.drawContours(image, [largest_contour], -1, (0, 255, 0), 2)

    plt.imshow(image, cmap="gray")
    plt.title("Canny Edge Detection")
    plt.axis("off")
    plt.show()


    Problems I'm Facing:


    • The detected contours sometimes include the image border or noise instead of just the lake.


    • I want to calculate the perimeter and area of the lake, but I am not sure if I am selecting the correct contour.

    Expected Output:


    • Extract only the lake contour from the image.


    • Compute the perimeter and area .

    Question:


    • How can I ensure that I am only selecting the lake's contour and not unwanted edges?


    • What is the best way to calculate the lake's area and perimeter
      correctly?


    • Should I preprocess the image differently (e.g., thresholding,
      morphological operations)?

    Images:

    code output image: https://i.sstatic.net/mLCvT5sD.png

    mask image that I use in code (water_body_3.jpg): https://i.sstatic.net/psXSsJfg.jpg

    original image:https://i.sstatic.net/4v6f4wLj.jpg

    Continue reading...

Compartilhe esta Página