C语言实现游程(行程)长度编码——RLC/RLE
程序员文章站
2022-03-11 14:44:37
...
#include <iostream>
#define LINE 256
#define ROW 256
#define SIZE 256*256
using namespace std;
int main()
{
unsigned char ImageRAW[256][256];
unsigned char ImageTra[256][256];
unsigned char line[ROW*LINE];
unsigned char line_Decode[ROW*LINE]; //解码像素向量
int RLC[ROW * LINE + 1];
int RLC_Decode[ROW * LINE + 1]; //解码RLC
FILE *fp;
long i,j,k,m;
long count = 1;
if((fp = fopen("sy1.raw","rb")) != 0)
{
fread(ImageRAW, 1, ROW * LINE, fp);
fclose(fp);
}
//二值化
for(i = 0; i < 256; i++)
{
for(j =0; j<256; j++)
{
if(ImageRAW[i][j] > 100)
ImageRAW[i][j] = 255;
else
ImageRAW[i][j] = 0;
}
}
//存储原图
if((fp = fopen("sy4_source.raw", "wb")) != 0)
{
fwrite(ImageRAW, 1, ROW*LINE, fp);
fclose(fp);
}
//RLC编码
//转成行
for(i = 0,k = 0; i < LINE; i++)
{
for(j = 0; j < ROW; j++)
{
line[k] = ImageRAW[i][j];
++k;
}
}
//初始化RLC[]为0
for(k = 0; k < ROW * LINE ; k++)
{
RLC[k] = 0;
RLC_Decode[k] = 0;
}
//编码
for ( i = 1,k = 0; i < SIZE; i++)
{
if (line[i] == line[i-1])
{
++count;
}
else
{
if (line[i-1] == 255)
{
RLC[k] = 255;
RLC[k+1] = count;
k = k + 2;
count = 1;
}
if (line[i-1] == 0)
{
RLC[k] = 0;
RLC[k+1] = count;
k = k + 2;
count = 1;
}
}
}
//最后一个字符单独处理
if (line[--i] == 0)
{
RLC[k] = 0;
RLC[k+1] = count;
}else
{
RLC[k] = 0;
RLC[k+1] = count;
}
//存编码文件 k+2 6444
if((fp = fopen("sy4_RLC.txt", "wb")) != 0)
{
fwrite(RLC, sizeof(int), k + 2, fp);
fclose(fp);
}
//获取文件长度 fSize 25780byte
fp = fopen("sy4_RLC.txt","r");
fseek(fp,sizeof(int),SEEK_END);
long fSize = ftell(fp);
long aSize = (fSize/4) - 1;
//读编码文件
if((fp = fopen("sy4_RLC.txt","rb")) != 0)
{
fread(RLC_Decode, sizeof(int), fSize, fp);
fclose(fp);
}
//解码
for (i = 0,k = 0; i < aSize-1; i = i+2)
{
for ( j = 0; j < RLC_Decode[i+1]; j++)
{
line_Decode[k] = RLC_Decode[i];
++k;
}
}
//转成矩阵
for ( i = 0,j = 0,k = 0; i < ROW*LINE; i++)
{
if(k == 256)
{
j++;
k=0;
}
ImageTra[j][k] = line_Decode[i];
k++;
}
system("pause");
}