从轮廓提取图像

2024-10-02 08:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: from图像imageimportnumpydatapilnp
2条回答

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

如果你想把不在轮廓内的一切都归零,你应该研究如何确定一个点是否在多边形内,然后把不在轮廓内的每个点归零。在

其中contours是使用measure.find_contours找到的计数列表,x是您的图像。这演示了如何执行矩形边界框提取image_patch,以及如何提取多边形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()

相关问题 更多 >

    热门问题