天天看點

C語言實作raw格式圖像的讀入和存取C語言實作raw格式圖像的讀入和存取

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格式的圖像一般情況下不能直接打開,需要有專門的工具才能打開,大家可以使用程式對其資料進行讀寫,進而實作圖像算法處理的過程。

繼續閱讀