アルゴリズムが PPM 画像を正常に読み取るのに非常に苦労しています...一部の画像では完全に機能しますが、他の画像ではうまく機能せず、半分の灰色 (RGB 205、205、205) の画像になります。
私は見つけることができるすべてを試し、何時間も研究しました。もう1週間止まってる…
皆さんが助けてくれることを願っています。
Image* pnm_read(char* filePath)
{
FILE* file;
char token[20];
int imageWidth, imageHeight, maximumColorValue;
Image* image;
/* Abre arquivo PNM. */
file = fopen(filePath, "r");
if (file == NULL)
{
fprintf(stderr, "Não foi possível localizar o arquivo de imagem %s.\n", filePath);
return 0;
}
/* Lê Magic Number do cabecalho e vê se é P6*/
pnm_get_token(file, token, sizeof token);
if (strcmp(token, "P6"))
{
fprintf(stderr, "%s não é um arquivo PPM válido.\n", filePath);
fclose(file);
return 0;
}
//Lê widht, height e valor máximo rgb
if (sscanf(pnm_get_token(file, token, sizeof token), "%d", &imageWidth) != 1 ||
sscanf(pnm_get_token(file, token, sizeof token), "%d", &imageHeight) != 1 ||
sscanf(pnm_get_token(file, token, sizeof token), "%d", &maximumColorValue) != 1)
{
fprintf(stderr, "%s não é um arquivo PNM válido.\n", filePath);
fclose(file);
return 0;
}
//Se não for RGB com componentes de 8 bits (0-255) dá erro
if (maximumColorValue != 255)
{
fprintf(stderr, "%s does not have 8-bit components: maximumColorValue=%d\n", filePath, maximumColorValue);
fclose(file);
return 0;
}
image = new Image(imageWidth, imageHeight);
unsigned char* pixelComponents = new unsigned char[imageWidth * imageHeight * 3];
fread(pixelComponents, sizeof(unsigned char), imageWidth * imageHeight * 3, file);
fclose(file);
int r, g, b, pixel;
for(int i = 3; i <= imageWidth * imageHeight * 3; i += 3)
{
r = pixelComponents[i-3] & 0xff;
g = pixelComponents[i-2] & 0xff;
b = pixelComponents[i-1] & 0xff;
/*fread(&r, sizeof(char), sizeof(char), file);
fread(&g, sizeof(char), sizeof(char), file);
fread(&b, sizeof(char), sizeof(char), file);
r = r & 0xff;
g = g & 0xff;
b = b & 0xff;*/
pixel = (255 << 24) | (r << 16) | (g << 8) | b;
// Atribuindo os pixels e virando imagem de cabeca para baixo
image->pixels[ (imageWidth * imageHeight) - (i/3) - 1] = pixel;
}
printf("Lido arquivo PNM (%s): %dx%d pixels.\n", filePath, image->width, image->height);
return image;
}