0

I'm looking to cut up image data into regularly sized screen blocks. Currently the method I've been using is this:

def getScreenBlocksFastNew(bmpstr):
    pixelData = array.array('c')

    step = imgWidth * 4
    pixelCoord = (blockY * blockSizeY * imgWidth +
                  blockSizeX * blockX)* 4
    for y in range(blockSizeY):
        pixelData.extend( bmpstr[pixelCoord : pixelCoord + blockSizeX * 4] )
        pixelCoord += step    
    return pixelData

bmpstr is a string of the raw pixel data, stored as one byte per RGBA value. (I also have the option of using a tuple of ints. They seem to take about the same amount of time for each). This creates an array of a block of pixels, depicted by setting blockX, blockY and blockSizeX, blockSizeY. Currently blockSizeX = blockSizeY = 22, which is the optimal size screen block for what I am doing.

My problem is that this process takes .0045 seconds per 5 executions, and extrapolating that out to the 2000+ screen blocks to fill the picture resolution requires about 1.7 seconds per picture, which is far too slow.

I am looking to make this process faster, but I'm not sure what the proper algorithm will be. I am looking to have my pixelData array pre-created so I don't have to reinstantiate it every time. However this leaves me with a question: what is the fastest way to copy the pixel RGBA values from bmpstr to an array, without using extend or append? Do I need to set each value individually? That can't be the most efficient way.

For example, how can I copy values bmpstr[0:100] into pixelData[0:100] without using extend or setting each value individually?

Trevor
  • 995
  • 3
  • 10
  • 25
  • Can you use numpy? If so, I would suggest blasting through the string in one pass and dumping all of the data into an `np.ndarray` and then pull the data out of that via numpy slicing magic. (numpy is one of my hammers, it solves all problems) – tacaswell Oct 02 '13 at 05:46
  • maybe look at buffer/memoryview? http://stackoverflow.com/questions/3422685/what-is-python-buffer-type-for/3422740#3422740 – Corley Brigman Oct 02 '13 at 13:41

0 Answers0