使用 openCV-python 将两个轮廓分割成两个相同大小的不同图像

Segmenting two contours into two different images of same size using openCV-python

我在第一个 image. I need to segment out individual contours and make two images out of it like this: image1 and image2 中有两个轮廓。单个输出图像必须与输入图像具有相同的尺寸。如何使用 openCV-python 来实现?我绘制等高线的代码:

    image, contours, hier = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for c in contours:
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    # convert all coordinates floating point values to int
    box = np.int0(box)
    # draw a red 'nghien' rectangle
    cv2.drawContours(im, [box], 0, (0, 0, 255))
    cv2.drawContours(im, contours, -1, (255, 255, 0), 1)

您使用 cv2.drawContours 的方式有误。传递 -1 作为轮廓索引将绘制所有轮廓而不是单个轮廓。要绘制单个轮廓,您需要将相应的索引传递为:

_, cnt, hierarchy = cv2.findContours(canvas.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for i in xrange(len(cnt)):
    output_canvas = np.zeros(canvas.shape, dtype=np.uint8)
    cv2.drawContours(output_canvas, cnt, i, np.array([255, 255, 255, 255]), -1)
    cv2.imwrite("./contour{}.png".format(i), output_canvas)