2011-08-19 71 views
4

什麼是創造PySide圖像(QImage的)直方圖的最有效方法是什麼?的Python/Pyside:創建圖像直方圖

我的測試圖像是1,9MB,3648x2736px,JPEG照片

我嘗試兩種方式:

1.

import time 
start = time.time() 

for y in range(h): 
    line = img.scanLine(y) # img - instance of QImage 
    for x in range(w): 
     color = struct.unpack('I', line[x*4:x*4+4])[0] 
     self.obrhis[0][QtGui.qRed(color)] += 1 # red 
     self.obrhis[1][QtGui.qGreen(color)] += 1 # green 
     self.obrhis[2][QtGui.qBlue(color)] += 1 # blue 

print 'time: ', time.time() - start 

平均時間= 15秒

2。

import time 
start = time.time() 

buffer = QtCore.QBuffer() 
buffer.open(QtCore.QIODevice.ReadWrite) 
img.save(buffer, "PNG") 

import cStringIO 
import Image 

strio = cStringIO.StringIO() 
strio.write(buffer.data()) 
buffer.close() 
strio.seek(0) 
pilimg = Image.open(strio) 

hist = pilimg.histogram() 
self.obrhis[0] = hist[:256] 
self.obrhis[1] = hist[256:512] 
self.obrhis[2] = hist[512:] 

print 'time: ', time.time() - start 

平均時間= 4S

更好,但仍然緩慢。 有沒有更快的方法來計算QImage的圖像直方圖?

+0

你所說的「最有效」的意思是?:最簡單的代碼?最快的處理?使用最少的內存? – ewall

+0

最快處理是我的目標 – DooBLER

+0

通過對兩種不同的方法進行計時,您已經處於一個良好的開端。你可以嘗試循環/的作用中計算(如[那些在這個問題上市(http://stackoverflow.com/questions/2870466/python-histogram-one-liner))的方式不同,但它很難[確定性能瓶頸與代碼分析等](http://stackoverflow.com/questions/3956112/how-to-determine-bottlenecks-in-code-besides-visual-inspection)。 – ewall

回答

0

你可以嘗試另一種方法是獲得圖像數據轉換成numpy的陣列(希望能夠合理有效),並使用numpy.histogram