使用openCV-python

时间:2018-12-08 07:16:42

标签: python opencv image-processing opencv-contour

在第一个image中有两个轮廓。我需要分割出各个轮廓,并像这样image1image2来制作出两个图像。单个输出图像必须与输入图像具有相同的尺寸。如何使用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)

1 个答案:

答案 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)