gpt4 book ai didi

python - 如何裁剪轮廓的内部区域?

转载 作者:太空狗 更新时间:2023-10-29 17:01:56 27 4
gpt4 key购买 nike

我正在研究视网膜眼 basemap 像。该图像由黑色背景上的圆形视网膜组成。使用 OpenCV,我设法获得了围绕整个圆形 Retina 的轮廓。我需要的是从黑色背景中裁剪出圆形视网膜。

最佳答案

您的问题中不清楚您是要实际裁剪轮廓内定义的信息还是屏蔽与所选轮廓无关的信息。我将探讨在这两种情况下该怎么做。


隐藏信息

假设您运行了 cv2.findContours在您的图像上,您将收到一个结构,其中列出了图像中所有可用的轮廓。我还假设您知道用于包围所需对象的轮廓的 index。假设这存储在 idx 中,首先使用 cv2.drawContours将此轮廓的填充版本绘制到空白图像上,然后使用此图像索引到您的图像中以提取出对象。此逻辑屏蔽任何不相关的信息,只保留重要的信息 - 这是在您选择的轮廓内定义的。执行此操作的代码如下所示,假设您的图像是存储在 img 中的灰度图像:

import numpy as np
import cv2
img = cv2.imread('...', 0) # Read in your image
# contours, _ = cv2.findContours(...) # Your call to find the contours using OpenCV 2.4.x
_, contours, _ = cv2.findContours(...) # Your call to find the contours
idx = ... # The index of the contour that surrounds your object
mask = np.zeros_like(img) # Create mask where white is what we want, black otherwise
cv2.drawContours(mask, contours, idx, 255, -1) # Draw filled contour in mask
out = np.zeros_like(img) # Extract out the object and place into output image
out[mask == 255] = img[mask == 255]

# Show the output image
cv2.imshow('Output', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

如果你真的想裁剪...

如果要裁剪图像,需要定义轮廓定义区域的最小跨度边界框。您可以找到边界框的左上角和右下角,然后使用索引裁剪出您需要的内容。代码将与以前相同,但会有一个额外的裁剪步骤:

import numpy as np
import cv2
img = cv2.imread('...', 0) # Read in your image
# contours, _ = cv2.findContours(...) # Your call to find the contours using OpenCV 2.4.x
_, contours, _ = cv2.findContours(...) # Your call to find the contours
idx = ... # The index of the contour that surrounds your object
mask = np.zeros_like(img) # Create mask where white is what we want, black otherwise
cv2.drawContours(mask, contours, idx, 255, -1) # Draw filled contour in mask
out = np.zeros_like(img) # Extract out the object and place into output image
out[mask == 255] = img[mask == 255]

# Now crop
(y, x) = np.where(mask == 255)
(topy, topx) = (np.min(y), np.min(x))
(bottomy, bottomx) = (np.max(y), np.max(x))
out = out[topy:bottomy+1, topx:bottomx+1]

# Show the output image
cv2.imshow('Output', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

裁剪代码的工作原理是,当我们定义掩码以提取轮廓定义的区域时,我们还会找到定义轮廓左上角的最小水平和垂直坐标。我们类似地找到定义轮廓左下角的最大水平和垂直坐标。然后我们使用这些坐标的索引来裁剪我们实际需要的内容。请注意,这会对蒙版 图像执行裁剪 - 即移除除最大轮廓内包含的信息以外的所有内容的图像。

注意 OpenCV 3.x

需要注意的是,以上代码假定您使用的是 OpenCV 2.4.x。请注意,在 OpenCV 3.x 中,cv2.findContours 的定义已更改。具体来说,输出是一个三元素元组输出,其中第一个图像是源图像,而其他两个参数与 OpenCV 2.4.x 中的相同。因此,只需更改上面代码中的cv2.findContours语句即可忽略第一个输出:

_, contours, _ = cv2.findContours(...) # Your call to find contours

关于python - 如何裁剪轮廓的内部区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28759253/

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