C语言实现raw格式图像的读入和存取
raw格式是在生活中比较少见的图像格式,但是它作为一种相机的原始图像数据,在图像处理领域用处很多。raw格式的图像相当于就是一个二进制流,所有图像数据按顺序单字节存放,中间没有任何间隔,自然也不存在所谓的每一行一个回车,它的每个图像数据都是紧挨着的,读取的时候必须自己按照图像的分辨率进行存取,放在二维数组中的情况居多,当存取到二维数组中时才有了行和列的概念。下面给出C语言实现的读入和存取raw图像。
/*========================================================================*/
//
// Description: 针对RAW图像的读入和存取
//
// Arguments:
//
// Returns:
//
// Notes: none
//
// Time: none
//
// Memory: none
//
// Example: none
//
// History: 1. wangyi 2014-4-19 22:46 Verison1.00 create
/*========================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define height 256
#define width 256
typedef unsigned char BYTE; // 定义BYTE类型,占1个字节
int main()
{
FILE *fp = NULL;
BYTE B[height][width];
BYTE *ptr;
char path[256];
char outpath[256];
int i,j;
// 输入源路径并打开raw图像文件
printf("Input the raw image path: ");
scanf("%s",path);
if((fp = fopen( path, "rb" )) == NULL)
{
printf("can not open the raw image " );
return;
}
else
{
printf("read OK");
}
// 分配内存并将图像读到二维数组中
ptr = (BYTE*)malloc( width * height * sizeof(BYTE) );
for( i = 0; i < height; i++ )
{
for( j = 0; j < width ; j ++ )
{
fread( ptr, 1, 1, fp );
B[i][j]= *ptr; // 把图像输入到2维数组中,变成矩阵型式
printf("%d ",B[i][j]);
ptr++;
}
}
fclose(fp);
// 这里可以对二维数组中的图像数据进行处理
// 将处理后的图像数据输出至文件
printf("Input the raw_image path for save: ");
scanf("%s",outpath);
if( ( fp = fopen( outpath, "wb" ) ) == NULL )
{
printf("can not create the raw_image : %s\n", outpath );
return;
}
for( i = 0; i < height; i++ )
{
for( j = 0; j < width ; j ++ )
{
fwrite( &B[i][j], 1 , 1, fp );
}
}
fclose(fp);
}
上述程序实现了读入和存取的功能,中间可以自己加入对图像数据的处理算法,如注释中所述即可。
总之,raw格式的图像一般情况下不能直接打开,需要有专门的工具才能打开,大家可以使用程序对其数据进行读写,从而实现图像算法处理的过程。