Python/Pyside: Create Image Histogram
What is the most effective way to create an image (QImage) histogram in PySide?
My test image is 1,9MB, 3648x2736px, jpeg photo
I tried two ways:
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
average time = 15s
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(buff开发者_如何转开发er.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
average time = 4s
Better but still slow. Is there a faster way to calculate image histogram from QImage?
Another approach you might try is getting the image data into a numpy array (hopefully possible reasonably efficiently) and using numpy.histogram.
精彩评论