我想将图片保存为' JPEG'使用不同的质量设置,然后再次加载它,并读出量化矩阵。对于每个质量参数,它们的矩阵应该是不同的。
以下代码应该这样做:
from PIL import Image
im_path = '~/Pictures/Origianl.JPG' # path to original image
im_path_tmp = '~/Pictures/DifferentQuality_' # trunk of path to images of lower quality
im = Image.open(im_path) # load original image
qs = {} # empty dictionary to save quantization matrices
qs['orig'] = im.quantization[0] # also remember q-matrix of original image
for i, qual in enumerate(range(100,-1,-10)): # run over 10 different quality parameters
curr_path = im_path_tmp + str(qual) + '.JPG' # each image gets its own path
print('iteration: {:2d}, curr_quality={:03d},curr_path={}'.format(i,qual,curr_path))
im.save(curr_path, 'JPEG', qualilty=qual) # save image: quality-parameter is set!
tmp = Image.open(curr_path) # load image again
qs[qual] = tmp.quantization[0] # read out q-matrix and save to dict
del tmp
del curr_path
print()
for key, value in qs.items(): # show all q-matrices
print('{}:\n\t{}'.format(key,value[0:32]))
我现在期待10种不同的q-矩阵。虽然它们都完全相同:
orig:
array('B', [2, 2, 2, 2, 2, 2, 3, 2, 2, 3, 5, 3, 3, 3, 5, 6, 5, 5, 5, 5, 6, 8, 6, 6, 6, 6, 6, 8, 10, 8, 8, 8])
100:
array('B', [8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 13, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26])
90:
array('B', [8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 13, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26])
80:
array('B', [8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 13, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26])
70:
array('B', [8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 13, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26])
60:
array('B', [8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 13, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26])
# and so on ...
请注意,它从orignal更改为所有其他人。 如果我手动保存它,就像在python-interpreter中一样,它可以工作,原因有些奇怪:
In [90]: im.save('~/Pictures/manual.JPG', 'JPEG', quality=70)
In [91]: tmp = Image.open('~/Pictures/manual.JPG')
In [92]: tmp.quantization[0]
Out[92]: array('B', [10, 7, 7, 8, 7, 6, 10, 8, 8, 8, 11, 10, 10, 11, 14, 24, 16, 14, 13, 13, 14, 29, 21, 22, 17, 24, 35, 31, 37, 36, 34, 31, 34, 33, 38, 43, 55, 47, 38, 41, 52, 41, 33, 34, 48, 65, 49, 52, 57, 59, 62, 62, 62, 37, 46, 68, 73, 67, 60, 72, 55, 61, 62, 59])
如果手动完成,为什么行为会有所不同。 我最好的猜测是,解释器会优化某些功能。如果是这样,我该如何关闭它?我使用Anaconda python 3.6.1运行ipython作为解释器,这是有帮助的。
答案 0 :(得分:0)
感谢@ ch7kor,他指出保存功能的签名中存在拼写错误。我通过" qual IL ity"而不是"质量"
这解决了我的实际问题。
并提出下一个问题,为什么不抛出任何错误。我怀疑这个参数(有拼写错误)存在于函数的签名中......