Created
March 4, 2011 18:43
-
-
Save suapapa/855470 to your computer and use it in GitHub Desktop.
img2rawdump.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# img2rawdump.py - dump raw date from input image | |
# | |
# Copyright (C) 2011 Homin Lee <[email protected]> | |
# | |
# This program is free software; you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation; either version 2 of the License, or | |
# (at your option) any later version. | |
import Image | |
def toYCbCr422(pixels): | |
r1, g1, b1, a1 = pixels[0] | |
r2, g2, b2, a2 = pixels[1] | |
y1 = int(0.299 * r1 + 0.587 * g1 + 0.114 * b1) | |
cb1 = 0.564 * (b1 - y1) | |
cr1 = 0.713 * (r1 - y1) | |
y2 = int(0.299 * r2 + 0.587 * g2 + 0.114 * b2) | |
cb2 = 0.564 * (b2 - y2) | |
cr2 = 0.713 * (r2 - y2) | |
cb = int((cb1 + cb2) / 2) | |
cr = int((cr1 + cr2) / 2) | |
return map(lambda x:x&0xff, (y1, cb, cr, y2, cb, cr)) | |
def toRGB565(pixels): | |
r, g, b, a = pixels[0] | |
b1 = ((r >> 3) << 3) + ((g >> 2) >> 3) | |
b2 = ((g >> 2) << 5) + (b >> 3) | |
return map(lambda x:x&0xff, (b2, b1)) # should swap the edian | |
convertDict = { | |
'YCbCr422': (2, toYCbCr422), | |
'RGB565': (1, toRGB565), | |
} | |
if __name__ == '__main__': | |
from optparse import OptionParser | |
optPsr = OptionParser("usage: %prog [-f FMT] input_imgs") | |
optPsr.add_option('-f', '--fmt', type='string', | |
help="format: 'YCbCr422 or RGB565") | |
(opts, args) = optPsr.parse_args() | |
cStep, cFunc = convertDict[opts.fmt] | |
for imgPath in args: | |
img = Image.open(imgPath) | |
dumpPath = imgPath + '_%dx%d.'%img.size + opts.fmt | |
wp = open(dumpPath, 'wb') | |
imgData = map(ord, list(img.tostring())) | |
while(imgData): | |
pixels = [] | |
for i in range(cStep): | |
r = imgData.pop(0) | |
g = imgData.pop(0) | |
b = imgData.pop(0) | |
if img.mode == 'RGBA': | |
a = imgData.pop(0) | |
else: | |
a = 0xff | |
pixels.append((r,g,b,a)) | |
retDump = cFunc(pixels) | |
wp.write(''.join(map(chr, retDump))) | |
wp.close() | |
# vim: et sw=4 fenc=utf-8: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment