【问题标题】:Extracting images from contours从轮廓中提取图像
【发布时间】:2013-12-17 02:17:53
【问题描述】:

我试图弄清楚如何制作一个脚本,从一张图像中剪切出图像。得到图像的轮廓后,我不明白该怎么做。我的思路是加载一张表,将其转换为灰度,找到轮廓,使用它们从原始彩色图像中剪切图像并单独保存。

import numpy as np
from sys import argv
from PIL import Image
from skimage import measure

# Inicialization
spritesToFind = argv[1]
spriteSize = argv[2]
sheet = Image.open(argv[3])

# To grayscale, so contour finding is easy
grayscale = sheet.convert('L')

# Let numpy do the heavy lifting for converting pixels to black or white
data = np.asarray(grayscale).copy()

# Find the contours we need
contours = measure.find_contours(data, 0.8)

# Now we put it back in PIL land

sprite = Image.fromarray(data)
sprite.save(str(spritesToFind), "PNG")

【问题讨论】:

  • 答案将取决于图像的外观。您也许可以使用 find_contours,但您可能需要更复杂的东西。

标签: python image python-2.7 scipy


【解决方案1】:

如果你只想剪掉包含轮廓的最小矩形,你可以使用轮廓中的 (x,y) 坐标来创建一个从 (min(x), min(y)) 到 (max) 的边界框(x),max(y))。

如果您想将不在轮廓内的所有内容归零,您应该研究如何确定一个点是否在多边形内,然后将不在轮廓内的每个点归零。

【讨论】:

  • 我想剪出包含轮廓的最小矩形,有很多轮廓。恐怕我不明白这些东西是如何真正起作用的。能给我解释一下吗?
【解决方案2】:

其中contours 是使用measure.find_contours 找到的计数列表,x 是您的图像。这显示了如何提取矩形边界框 image_patch 以及如何提取 just 属于多边形 new_image 的像素:

from matplotlib import path

contour = contours[0]
path = path.Path(contour)

top = min(contour[:,0])
bottom = max(contour[:,0])
left = min(contour[:,1])
right = max(contour[:,1])

new_image = np.zeros([bottom-top,right-left])

for xr in range(new_image.shape[0]):
    for yr in range(new_image.shape[1]):        
        if(path.contains_point([top+xr,left+yr])):
            new_image[xr, yr] = x[top+xr, left+yr]


image_patch = x[top:bottom,left:right]

plt.imshow(image_patch)
plt.show()

plt.imshow(new_image)
plt.show()

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 2012-11-15
    • 2022-01-26
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2020-05-08
    相关资源
    最近更新 更多