[Python] How to group contours and draw a single bounding rectangle

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

  1. Stack

    Stack Membro Participativo

    I need to group contours and draw a single bounding rectangle that encloses all the contours, something like this

    [​IMG]

    from matplotlib import pyplot as plt
    import cv2 as cv

    img = cv.imread('shapes1.png', 0)
    imgRGB = cv.cvtColor(img.copy(), cv.COLOR_GRAY2RGB)

    _, ctrs, _ = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    boxes = []
    for ctr in ctrs:
    x, y, w, h = cv.boundingRect(ctr)
    boxes.append([x, y, w, h])

    for box in boxes:
    top_left = (box[0], box[1])
    bottom_right = (box[0] + box[2], box[1] + box[3])
    cv.rectangle(imgRGB, top_left, bottom_right, (0,255,0), 2)

    fig = plt.figure(figsize = (10, 10))
    ax = fig.add_subplot(111)
    ax.imshow(imgRGB, cmap='gray')


    [​IMG]

    Is there any straight forward way to do it rather than merging all bounding rectangles programmatically

    Continue reading...

Compartilhe esta Página