4

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(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

average time = 4s

Better but still slow. Is there a faster way to calculate image histogram from QImage?

shobhit
  • 702
  • 2
  • 9
  • 21
DooBLER
  • 1,180
  • 1
  • 7
  • 8
  • What do you mean by "most effective"?: easiest to code? fastest processing? uses the least memory? – ewall Aug 19 '11 at 15:19
  • fastest processing is my target – DooBLER Aug 19 '11 at 15:22
  • You're off to a good start by timing two different methods. You could try different ways of looping/interating the calculation (such as [those listed in this question](http://stackoverflow.com/questions/2870466/python-histogram-one-liner)), but it's harder to [identify the performance bottlenecks with code profiling and such](http://stackoverflow.com/questions/3956112/how-to-determine-bottlenecks-in-code-besides-visual-inspection). – ewall Aug 19 '11 at 15:39

1 Answers1

0

Another approach you might try is getting the image data into a numpy array (hopefully possible reasonably efficiently) and using numpy.histogram.

timday
  • 24,582
  • 12
  • 83
  • 135