【发布时间】:2020-01-16 20:02:20
【问题描述】:
我有一个包含大约 3000 张图像的数据集,如果我有它们位置的边界框坐标,我想裁剪每个图像的多个区域。唯一的问题是我的代码非常慢,我尝试过分析和使用 Cython,但有边际改进。我正在使用 Pillow 库进行裁剪,他们可能是实现此任务的更快方法吗?
边界框位置存储在 CSV 文件中。下面的代码遍历每个文件
train_label=pd.read_csv("train.csv")
for i in range(len(train_label.index)):
name=train_label["image_id"][i]; labels=train_label["labels"][i];
split_images(name,labels)
以及下面的重载功能。
def split_images(name, labels):
boundingboxes = np.array(labels.split(' ')).reshape(-1, 5)
for (unicode, x, y, w, h) in boundingboxes:
try:
# Create target Directory
os.mkdir('unicodes/{}'.format(str(unicode)))
except FileExistsError:
None
(x, y, w, h) = (int(x), int(y), int(w), int(h))
imsource = Image.open('train_images/{}.jpg'.format(name))
cropped_image = imsource.crop((x, y, x + w, y + h))
cropped_image.save('unicodes/{}/{}.jpg'.format(unicode, name))
如果有帮助,我将在 Google 云平台上远程运行代码。
【问题讨论】:
-
每张图像的裁剪区域是否总是相同,或者至少总是相同数量的裁剪?使用您的代码,您可以多次打开和关闭图像,每次裁剪一次。 ImageMagick 可以打开图像一次并使用括号处理在多个位置进行裁剪,如果您创建的命令提前知道所有裁剪。您还可以将图像一次转换为内存映射格式,以便每次打开都更快。您也可以查看 VIPS。它甚至是一个更快的工具,虽然我没有使用它的经验。
-
恐怕每个图像都不同。干杯我会检查出来!
-
如果你有一个不错的 CPU,多线程或多处理可能会给你带来显着的加速......类似于让你从这里开始 stackoverflow.com/a/51822265/2836621
标签: python performance image-processing python-imaging-library