Android培训班(29)

本文详细解析了带抖动转换的565颜色算法实现原理及过程,介绍了如何通过误差扩散来实现图像的颜色转换,并展示了具体的C语言代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->

接着来分析带抖动转换的565算法:

void to_565_raw_dither(int width)

{

unsigned char in[3];

unsigned short out;

int i = 0;

int e;

创建两个点的误差保存数组。

int* error = malloc((width+2) * 3 * sizeof(int));

int* next_error = malloc((width+2) * 3 * sizeof(int));

清空误差数组。

memset(error, 0, (width+2) * 3 * sizeof(int));

memset(next_error, 0, (width+2) * 3 * sizeof(int));

计算数组是使用三个点误差来计算,所以从-3开始。

error += 3; // array goes from [-3..((width+1)*3+2)]

next_error += 3;

读取原文件里的数据。

while(read(0, in, 3) == 3) {

计算当前点的值,当然这里已经使用以前点值进行扩散。

int r = in[0] + error[i*3+0];

int rb = (r < 0) ? 0 : ((r > 255) ? 255 : r);

int g = in[1] + error[i*3+1];

int gb = (g < 0) ? 0 : ((g > 255) ? 255 : g);

int b = in[2] + error[i*3+2];

int bb = (b < 0) ? 0 : ((b > 255) ? 255 : b);

out = to565(rb, gb, bb);

write(1, &out, 2);

计算误差值,以便下一个点值进行颜色调整。

#define apply_error(ch) { \

next_error[(i-1)*3+ch] += e * 3 / 16; \

next_error[(i)*3+ch] += e * 5 / 16; \

next_error[(i+1)*3+ch] += e * 1 / 16; \

error[(i+1)*3+ch] += e - ((e*1/16) + (e*3/16) + (e*5/16)); \

}

当前计算出来的颜色,与565里恢复出来的误差值。

e = r - from565_r(out);

apply_error(0);

e = g - from565_g(out);

apply_error(1);

e = b - from565_b(out);

apply_error(2);

#undef apply_error

++i;

到最后,清空误差值。

if (i == width) {

// error <- next_error; next_error <- 0

int* temp = error; error = next_error; next_error = temp;

memset(next_error, 0, (width+1) * 3 * sizeof(int));

i = 0;

}

}

删除分配的空间。

free(error-3);

free(next_error-3);

return;

}


到这里就把这个简短的代码分析完成了,别看这么一段程序,它其实还是包括很多技术在里面的,比如shell的了解、565颜色编码、游程编码、色差抖动算法。因此,要写出上面这个程序,要懂得比较的广博的知识,谁说知识无用呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值