[Python] Document detect: how to get contours from this image with opencv

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    the image is processed by binary, how to get the contours from this file.

    [​IMG]

    wrong contours: [​IMG]

    my code:

    CANNY_THRESH1 = 50 #
    CANNY_THRESH2 = 150 #
    DILATE_ITER = 2 #
    ERODE_ITER = 1 #
    APPROX_POLY_EPSILON = 0.02 #
    MIN_AREA = 1000 #
    DEBUG = True #
    img = cv2.imread("debug_binary.jpg")
    orig = img.copy()

    #
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # =======================
    # find canny
    # =======================
    edges = cv2.Canny(gray, CANNY_THRESH1, CANNY_THRESH2)

    # =======================
    # morph process
    # =======================
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    morph = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
    morph = cv2.dilate(morph, kernel, iterations=DILATE_ITER)
    morph = cv2.erode(morph, kernel, iterations=ERODE_ITER)

    # =======================
    # find contours
    # =======================
    contours, _ = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    book_contours = []
    for cnt in contours:
    if cv2.contourArea(cnt) < MIN_AREA:
    continue
    # 多边形逼近
    epsilon = APPROX_POLY_EPSILON * cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, epsilon, True)
    if len(approx) == 4: # 只保留四边形轮廓
    book_contours.append(approx)

    # =======================
    # draw contours
    # =======================
    output = orig.copy()
    cv2.drawContours(output, book_contours, -1, (0, 0, 255), 3)

    Continue reading...

Compartilhe esta Página