使用PIL自动裁剪图像

2024-10-01 07:43:26 发布

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

我有一个文件夹,每个图像包含至少4个较小的图像。我想知道如何使用Python-PIL剪切出较小的图像,以便它们都作为独立的图像文件存在。幸运的是,有一个常量,背景是白色或黑色,所以我想我需要的是一种方法,通过搜索完全黑色或完全白色的行或列来剪切这些图像,下面是一个示例图像:

enter image description here

从上面的图像中,将有10个单独的图像,每个图像都包含一个数字。提前谢谢。在

编辑:我有另一个样本图像,这是更现实的意义上,一些较小的图像的背景是相同的颜色,他们所包含的图像。e、 g

enter image description here

它的输出是13个独立的图象,每个图象包含一个字母


Tags: 方法图像文件夹编辑示例pil图像文件数字
1条回答
网友
1楼 · 发布于 2024-10-01 07:43:26

使用scipy.n图像对于标签:

import numpy as np
import scipy.ndimage as ndi
import Image

THRESHOLD = 100
MIN_SHAPE = np.asarray((5, 5))

filename = "eQ9ts.jpg"
im = np.asarray(Image.open(filename))
gray = im.sum(axis=-1)
bw = gray > THRESHOLD
label, n = ndi.label(bw)
indices = [np.where(label == ind) for ind in xrange(1, n)]
slices = [[slice(ind[i].min(), ind[i].max()) for i in (0, 1)] + [slice(None)]
          for ind in indices]
images = [im[s] for s in slices]
# filter out small images
images = [im for im in images if not np.any(np.asarray(im.shape[:-1]) < MIN_SHAPE)]

相关问题 更多 >