gpt4 book ai didi

python - 将轮廓内的区域复制到另一个图像

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:25 25 4
gpt4 key购买 nike

我在 Python 中使用以下代码来查找图像中的轮廓:

import cv2

im = cv2.imread('test.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

现在我想将第一个轮廓内的区域复制到另一个图像,但我找不到任何说明如何执行此操作的教程或示例代码。

最佳答案

这是一个完整的示例。它输出所有轮廓有点矫枉过正,但我​​认为您可能会找到一种方法根据自己的喜好对其进行调整。也不确定你所说的复制是什么意思,所以我假设你只是想将轮廓输出到一个文件中。

我们将从这样的图像开始(在这种情况下,您会注意到我不需要对图像进行阈值处理)。下面的脚本可以分为 6 个主要步骤:

  1. Canny 过滤器找到边缘
  2. cv2.findContours 跟踪我们的轮廓,请注意我们只需要外部轮廓,因此需要 cv2.RETR_EXTERNAL 标志。
  3. cv2.drawContours 为我们的图像绘制每个轮廓的形状
  4. 遍历所有轮廓并在它们周围放置边界框。
  5. 使用盒子的x,y,w,h信息来帮助我们裁剪每个轮廓
  6. 将裁剪后的图像写入文件。

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()

关于python - 将轮廓内的区域复制到另一个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com