下面是一个完整的实例。这有点矫枉过正,它输出所有的轮廓,但我认为你可能会找到一种方法来调整它的喜好。也不确定你的意思是复制,所以我会假设你只是想输出到一个文件的轮廓。
我们将从像这样的图像开始(在这种情况下,您会注意到我不需要对图像进行阈值处理)。下面的脚本可以被分解成6个主要步骤:
- 坎尼过滤器来查找边缘
cv2.findContours
跟踪我们的轮廓,注意,我们只需要外部轮廓因此cv2.RETR_EXTERNAL
标志。
cv2.drawContours
绘制每个轮廓的形状到我们的图像
- 循环遍历所有轮廓,并围绕它们放置边界框。
- 使用我们盒子的
x,y,w,h
信息来帮助我们裁剪每个轮廓
- 将裁剪后的图像写入文件。
import cv2
image = cv2.imread('images/blobs1.png')
edged = cv2.Canny(image, 175, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image, contours, -1, (0,255,0), 3)
cv2.imshow("Show contour", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
for i,c in enumerate(contours):
rect = cv2.boundingRect(c)
x,y,w,h = rect
box = cv2.rectangle(image, (x,y), (x+w,y+h), (0,0,255), 2)
cropped = image[y: y+h, x: x+w]
cv2.imshow("Show Boxes", cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("blobby"+str(i)+".png", cropped)
cv2.imshow("Show Boxes", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
[drawContours](http://docs.opencv.org/2.4.2/modules/core/doc/drawing_functions.html#drawcontours)? –
或者更具体地说,使用'drawContours'来生成一个蒙版,然后您可以使用它来复制给定轮廓的原始内容。 –