我寫了一個簡單的函數來調整圖像的大小從1500x2000px到900x1200px。Python成像庫循環性能變得越來越慢重複
def resizeImage(file_list):
if file_list:
if not os.path.exists('resized'):
os.makedirs('resized')
i = 0
for files in file_list:
i += 1
im = Image.open(files)
im = im.resize((900,1200),Image.ANTIALIAS)
im.save('resized/' + files, quality=90)
print str(i) + " files resized successfully"
else:
print "No files to resize"
我使用timeit函數來測量運行一些示例圖像需要多長時間。這是一個結果的例子。
+---------------+-----------+---------------+---------------+---------------+
| Test Name | No. files | Min | Max | Average |
+---------------+-----------+---------------+---------------+---------------+
| Resize normal | 10 | 5.25000018229 | 5.31371171493 | 5.27186083393 |
+---------------+-----------+---------------+---------------+---------------+
但是,如果我重複測試的時間逐漸不斷增加即
+---------------+-----------+---------------+---------------+---------------+
| Test Name | No. files | Min | Max | Average |
+---------------+-----------+---------------+---------------+---------------+
| Resize normal | 10 | 5.36660298734 | 5.57177596057 | 5.45903467485 |
+---------------+-----------+---------------+---------------+---------------+
+---------------+-----------+---------------+---------------+---------------+
| Test Name | No. files | Min | Max | Average |
+---------------+-----------+---------------+---------------+---------------+
| Resize normal | 10 | 5.58739076382 | 5.76515489024 | 5.70014196601 |
+---------------+-----------+---------------+---------------+---------------+
+---------------+-----------+---------------+---------------+-------------+
| Test Name | No. files | Min | Max | Average |
+---------------+-----------+---------------+---------------+-------------+
| Resize normal | 10 | 5.77366483042 | 6.00337707034 | 5.891541538 |
+---------------+-----------+---------------+---------------+-------------+
+---------------+-----------+---------------+--------------+---------------+
| Test Name | No. files | Min | Max | Average |
+---------------+-----------+---------------+--------------+---------------+
| Resize normal | 10 | 5.91993466793 | 6.1294756299 | 6.03516199948 |
+---------------+-----------+---------------+--------------+---------------+
這是IM如何運行測試。
def resizeTest(repeats):
os.chdir('C:/Users/dominic/Desktop/resize-test')
files = glob.glob('*.jpg')
t = timeit.Timer(
"resizeImage(filess)",
setup="from imageToolkit import resizeImage; import glob; filess = glob.glob('*.jpg')"
)
time = t.repeat(repeats, 1)
results = {
'name': 'Resize normal',
'files': len(files),
'min': min(time),
'max': max(time),
'average': averageTime(time)
}
resultsTable(results)
我已將從機械硬盤驅動器處理的圖像移至SSD,問題依然存在。我也檢查了正在使用的內存,並且在所有運行中保持相當穩定,在26Mb左右達到頂點,該進程使用CPU的一個核心的12%左右。
展望未來,我喜歡嘗試多處理庫來提高速度,但我想首先了解這個問題的底部。
這是我的循環會導致性能下降的問題嗎?
如果刪除'im.save()'調用會發生什麼?我懷疑這是由於在這裏反覆寫入磁盤造成的。 –
是的磁盤寫入導致它減慢,當我刪除保存,時間實際上增加了每次運行。 @MartijnPieters你認爲這個函數適合加速多處理模塊嗎?即時將標記此問題關閉。 –
如果您的計算機具有多個CPU內核,則使用多處理功能可以加速該進程(因爲每個調整大小都在單獨的CPU內核上運行)。 –