请参阅PBM格式 [^]。
PBM文件包含可打印的ASCII标头和像素作为打包二进制数据。使用Python代码,您将从像素数据(无标题)创建列表并打印这些值。我不知道python在内部做什么,但我想它会从打包数据中创建一个字节(或整数)列表。
在你的C代码中你正在打印ASCII标头和打包数据。要获得类似的输出,请跳过C代码中的标题并解压缩数据字节:
// 在此处读取标题并获取图像的宽度和高度
int stride = width%8;
for(int i = 0; i< height; i ++)
{
for(int j = 0; j< width / 8; j ++)
{
unsigned data_byte =(unsigned)getc(pFile);
for(int k = 0; k< 8; k ++)
{
// < span class ="code-comment">这里的位顺序可能是错误的。
// 如果是这样,请检查掩码0x80并向左移动。
// 编辑:黑色是1,白色为零!
printf(" %d,", (data_byte& 1)?0:255 跨度>);
data_byte>> = 1;
}
}
if(stride)
{
unsigned data_byte =(unsigned)getc(pFile);
for(int k = 0; k< stride; k ++)
{
// 再次:也许是订单这里的位错误。
printf(" %d,", (data_byte& 1)?0:255 跨度>);
data_byte>> = 1;
}
}
}
[编辑]
To解析标题最好将整个文件内容读入内存(代码未经过测试但编译):
#include< stdio.h中>
#include< io.h>
#include< ctype.h>
// ...
FILE * pFile = fopen("result.pbm","rb");
//注意:对于Microsoft编译器,这些函数可能需要
//领先得分(_filelength,_fileno)
long file_len = filelength(fileno(pFile));
unsigned char * buffer =(unsigned char *)malloc(file_len);
fread(buffer,1,file_len,pFile);
fclose(pFile);
const char * header =(const char *)buffer;
//跳过幻数"P4"
while(isalnum(* header))header ++;
//跳过空格
while(isspace(* header))header ++;
//获取宽度
int width = atoi(header);
//跳过宽度
while(isdigit(* header))header ++;
//跳过空格
while(isspace(* header))header ++;
int height = atoi(header);
//跳过高度
while(isdigit(* header))header ++;
//跳过单个空格
header ++;
//指向第一个数据(像素)字节的指针
const unsigned char * data =(const unsigned char *)header;
//如果宽度不是8的倍数,则每行额外字节
int stride = width%8;
for(int i = 0; i< height; i ++)
{
for(int j = 0; j< width / 8; j ++)
{
unsigned data_byte = * data ++;
for(int k = 0; k< 8; k ++)
{
//这里的比特顺序可能是错误的。
//如果是这样,请检查掩码0x80并向左移动。
//编辑:黑色为1,白色为零!
printf("%d,",(data_byte& 1)?0:255);
data_byte>> = 1;
}
}
if(stride)
{
unsigned data_byte = * data ++;
for(int k = 0; k< stride; k ++)
{
//再次:也许这里的位顺序是错误的。
printf("%d,",(data_byte& 1)?0:255);
data_byte>> = 1;
}
}
}
免费(缓冲);