【发布时间】:2021-03-16 20:09:59
【问题描述】:
据我所知,我的代码(如下)按预期运行。我打开一个图像,然后在保存时迭代地生成具有不同设置的图像副本,特别是在该步骤修改质量和优化值。我的目标是确定我的用例的最佳参数是什么,但在运行脚本时我发现了我不理解的结果。
无论我将“质量”设置为什么,生成的 PNG 的大小都是相同的。在“优化”( true/false ) 之间切换时 PNG 文件大小发生了变化,但在调整质量时不会发生变化。
这是预期的还是我在下面的代码中出错了?
'''I want to see how small I can go with the best picture quality'''
from PIL import Image
import matplotlib.pyplot as plt
from pathlib import Path
import os
def make_lists(result_images):
'''Returns a dict of lists containing image size values'''
plot_dict = {}
for ext, val in result_images.items():
for opt, var in val.items():
plot_dict[f'{ext}-{opt}'] = var
return plot_dict
def draw_result(plot_dict):
'''Draws resulting image data as a graph'''
colors = ['green', 'red', 'blue', 'orange']
c = 0
for key, val in plot_dict.items():
plt.plot(val, color=colors[c], label=key)
c += 1
plt.legend()
plt.show()
def generate_images():
'''Generates N images with adjustments to optimization and quality with each output
leaving the size the same each time'''
im_path = 'full.jpg'
out_path = 'out'
if not os.path.exists(out_path):
os.makedirs(out_path)
im = Image.open(im_path)
new_im = im.resize(im.size, Image.ANTIALIAS)
qualities = [100, 75, 50, 25]
optimize = [True, False]
extens = ['png', 'jpg']
result_images = {}
for ext in extens:
result_images[ext] = {}
for opt in optimize:
result_images[ext][opt] = []
for q in qualities:
fpath = f'{out_path}/{q}{opt}.{ext}'
new_im.save(fpath, optimize=opt, quality=q)
footprint = Path(fpath).stat().st_size
result_images[ext][opt].append(footprint)
return result_images
result_images = generate_images()
plot_dict = make_lists(result_images)
draw_result(plot_dict)
【问题讨论】:
标签: python matplotlib python-imaging-library png