[Python] How to count overlapping aluminum profiles in an image with consistent cross-section?...

Discussão em 'Python' iniciado por Stack, Maio 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have an image showing several aluminum profile cross-sections, all with a consistent shape. However, due to overlapping, tilting, and plastic wrapping, it’s difficult to count them using traditional method

    [​IMG]

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

    # Load image
    image = cv2.imread("aluminum_profiles.png")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Edge detection
    edges = cv2.Canny(gray, 50, 150)

    # Morphological operations to clean up
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    cleaned = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)

    # Find contours
    contours, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Filter and count large contours
    count = 0
    for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > 1000: # Empirical threshold
    count += 1
    cv2.drawContours(image, [cnt], -1, (0, 255, 0), 2)

    print("Detected profiles:", count)

    # Show result
    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    plt.axis('off')
    plt.show()


    1. I tried OpenCV Canny edge detection and findContours(). However, overlapping shapes and packaging noise make it hard to isolate individual profiles.


    2. Using one aluminum profile as a template in cv2.matchTemplate() struggles when the shapes are rotated or partially occluded, and results in many false positives.


    3. With SIFT/ORB, matching keypoints were scattered, making it difficult to group them into distinct instances.

    All the above methods either overcount or fail to resolve individual profiles under occlusion and tilt.

    I want a robust method to count the aluminum profiles even under:
    • Partial occlusion.
    • Small rotations.
    • Noise (e.g., plastic wrapping).

    What would be a better approach for this type of repeated but imperfectly aligned object counting?

    Should I try LoFTR / SuperGlue for feature matching?

    Would training a lightweight instance segmentation model like YOLOv8 / Mask R-CNN be more effective?

    Or is there a traditional CV trick I’m missing?

    Appreciate any suggestions, examples, or implementation tips!

    Continue reading...

Compartilhe esta Página