Conversion of 24bit binary to int

Patrick Maupin pmaupin at speakeasy.net
Thu Nov 13 01:39:41 EST 2003


I just realized that, according to your spec, it ought to be possible
to do the rgb -> bgr0 conversion on the entire file all at one go
(no nasty headers or block headers to get in the way:)

So I wrote a somewhat more comprehensible (for one thing, it gets rid
of that nasty sum() everybody's been complaining about :), somewhat more
memory-intensive version of the program.  On my machine it executes at
approximately the same speed as the original one I wrote (10 source
megabytes/second), but this one might be more amenable to profiling
and further point optimizations if necessary.

The barebones (no comments or error-checking) functions are below.

Pat


import array

def RgbToBgr0(srcstring):
    srcarray = array.array('B',srcstring)
    dstarray = array.array('B',len(srcstring) * 4 // 3 * chr(0))
    for i in range(3):
        dstarray[2-i::4] = srcarray[i::3]
    return dstarray.tostring()

def deinterleave(srcstring,numchannels=6,pixelsperblock=512):
    bytesperblock = pixelsperblock*4
    totalblocks = len(srcstring) // bytesperblock
    blocknums = []
    for i in range(numchannels):
        blocknums.extend(range(i,totalblocks,numchannels))
    return ''.join([srcstring[i*bytesperblock:(i+1)*bytesperblock]
                 for i in blocknums])

def mungefile(srcname,dstname):
    srcfile = open(srcname,'rb')
    dstfile = open(dstname,'wb')
    dstfile.write(deinterleave(RgbToBgr0(srcfile.read())))
    srcfile.close()
    dstfile.close()




More information about the Python-list mailing list