首页 > 编程语言 > 详细

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

时间:2016-02-20 13:13:43      阅读:460      评论:0      收藏:0      [点我收藏+]

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[] = {...};  之类的。

在做图片显示的时候,下半部花屏, 想着有可能是python 的问题,由于有了下面,用 PHP 来提取颜色的。 

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 分散的方式很好,要是做位运算方便些。 

两个语言各有优势。

本来还想用 C# 来开发,就是装个 VS 实太需要太长时间。 人生苦短,我用python 。 

 

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

原文:http://www.cnblogs.com/ningci/p/5203053.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!