python 提取图片转为16 24BPP 的方法

python 中处理图片用的是 pil ,在 linux  和 win 上都可以使用。

centOS 5.x 上安装的方法是 yum install python-imaging

24BPP:

import Image
img = Image.open("1.jpg")
out = ""
width,height = img.size
for y in range(0, height):
    for x in range(0, width):
        r,g,b = img.getpixel((x, y))
        px = hex(r<<16 | g<<8 | b)
        out += str(px) + ","
        
print out

就是取像素的颜色在转为16进制,24BPP 的颜色,每位占8位。

 

16BPP:

import Image
img = Image.open("1.jpg")
out = ""
width,height = img.size
for y in range(0, height):
    for x in range(0, width):
        r,g,b = img.getpixel((x, y))
        #8bit convert to 5bit 
        px = hex((r>>3)<<11 | (g>>2)<<5 | b>>3)
        out += str(px) + ","
        
print out

2440 要求 分别占RGB 分别占 5 6 5 位。

程式只做了打印, 实际用的时候,可以通过 get24bbp.py > /home/24bpp.h  这样来使用。当然了,你还要手工编辑加上 static unsigned long img[] = {...};  之类的。

24BPP:

$out = "static const unsigned long img1[]={";

$img    = imagecreatefromjpeg("a.jpg");
$width  = imagesx($img);
$height = imagesy($img);
for($y=0;$y<$height;$y++)
{
    for($x=0;$x<$width;$x++)
    {
        $out .= sprintf("0x%X",imagecolorat($img,$x,$y)) . ',';
    }
}

$out .="0};\r\n";
file_put_contents("out.h",$out);

php 中使用 sprintf 转为 16进制,因为 php 我平时是在浏览器上运行的, 不能 > 导出, 所以加了 文件保存。

php 中文件保存很容易, python 中就要先 open 在 write 最后关闭。 但是 python 中, r g b 分散的方式很好,要是做位运算方便些。 

posted @ 2016-02-20 12:28  宁次  阅读(1784)  评论(0编辑  收藏  举报