[Python] How to identify contours using OpenCV or traditional methods?

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    Background: I currently have many grayscale images of steel. Some of them have high brightness, while others have uneven brightness. As shown in the figure below, how can I better extract their outlines?

    My method: First, I identify the approximate left and right boundaries to reduce the interference from background noise. Then, I perform the cropping. The code for processing the cropped part is as follows:

    m=img.shape[0]//2
    count=mayregion
    if clip_top:
    last_row = img_three[-1, :]
    mid_row= img_three[m, :]
    mean_pixel = (np.mean(last_row)+np.mean(mid_row))//2
    count=(np.sum(last_row > 240)+np.sum(mid_row>240))
    else:
    last_row = img_three[0, :]
    mid_row = img_three[m, :]
    mean_pixel = (np.mean(last_row) + np.mean(mid_row)) // 2
    count = (np.sum(last_row > 240) + np.sum(mid_row > 240))
    if mean_pixel>240:
    k=100
    elif mean_pixel>210:
    k=80
    else:
    k=30
    img_three_color = cv2.cvtColor(img_three, cv2.COLOR_GRAY2BGR)
    img_three = cv2.GaussianBlur(img, (7, 7), 1)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    img_open = cv2.morphologyEx(img_three, cv2.MORPH_OPEN, kernel)
    img_close = cv2.morphologyEx(img_open, cv2.MORPH_CLOSE, kernel)
    _, binary = cv2.threshold(img_close, k, 255, cv2.THRESH_BINARY)

    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) >= 100]
    cv2.drawContours(img_three_color, filtered_contours, -1, (0, 255, 0), 10)


    However, the contour obtained by this method still has some drawbacks.

    original image:

    [​IMG]

    The image obtained through my method (The green line represents the outline):

    [​IMG]

    Continue reading...

Compartilhe esta Página