【发布时间】:2021-07-08 18:30:37
【问题描述】:
我编写这个脚本是为了对大量 PNG 文件(总共大约 1500 个)进行一些图像处理。它们被组织成子目录。
这是我的代码:
from PIL import Image
import os
path = "/Some/given/path"
file_list = []
counter = 1
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".png"):
temp_file = {"path": os.path.join(root, file), "name": file}
file_list.append(temp_file)
for curr_file in file_list:
img = Image.open(curr_file["path"])
img = img.convert("RGBA")
val = list(img.getdata())
new_data = []
for item in val:
if item[3] == 0:
new_data.append(item)
else:
new_data.append((0, 0, 0, 255))
img.putdata(new_data)
file_name = "transform" + str(counter) + ".png"
replaced_text = curr_file["name"]
new_file_name = curr_file["path"].replace(replaced_text, file_name)
img.save(new_file_name)
counter += 1
文件夹结构如下:
Source folder
-- folder__1
-- image_1.png
-- image_2.png
-- image_3.png
-- folder__2
-- image_3.png
-- image_5.png
-- folder__3
-- image_6.png
在对单个图像进行测试时,图像处理只需几秒钟。但是,在运行脚本时,处理 15 张图像大约需要一个小时。关于我在哪里搞砸的任何建议?
【问题讨论】:
-
如果你想知道瓶颈在哪里,你应该做的第一件事是use the profiler。
-
使用snakeviz - jiffyclub.github.io/snakeviz 生成cprofile,然后将其可视化。
-
也就是说,要通过这种图像处理获得性能,您当然希望 get Numpy data 然后做 Numpy 的事情。
-
你真的不应该使用,甚至不应该考虑在 Python 中使用
for循环或带有图像的列表。像 Hans 展示的那样使用Numpy,然后,如果您有数千张图像,请在多核 CPU 时代使用multiprocessing。
标签: python python-3.x for-loop image-processing python-imaging-library