Py-*_*bie 5 python image-manipulation crop image-processing python-imaging-library
我有充满图像的文件夹,每个图像包含至少4个较小的图像.我想知道如何使用Python PIL剪掉较小的图像,以便它们都作为独立的图像文件存在.幸运的是有一个常数,背景是白色或黑色所以我猜我需要的是通过搜索行或最好是完全黑色或完全白色的列来切割这些图像的方法.这是一个示例图像:

从上图中可以看到10个单独的图像,每个图像都包含一个数字.提前致谢.
编辑:我有另一个样本图像更真实,因为一些较小图像的背景与它们所包含的图像背景颜色相同.例如

其输出为13个单独的图像,每个图像包含1个字母
使用 scipy.ndimage 进行标记:
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)]
Run Code Online (Sandbox Code Playgroud)