<!-- @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顏色編碼、遊程編碼、色差抖動演算法。因此,要寫出上面這個程式,要懂得比較的廣博的知識,誰說知識無用呢?