我正在开发一个转换器,将 PPM 从 P6(二进制)转换为 P3(ASCII)。由于 PPM 是一种原始格式,我认为我不会遇到质量损失,但由于某些无法解释的原因,转换时会发生这种情况:
原图:
转换后的图像:
这是我为这项工作编写的算法:
int convertP6toP3(char* fileName)
{
FILE *src, *dest;
char *outputFilename;
char magicNumber[3];
int height, width, depth;
unsigned char red, green, blue;
int i, j, widthCounter = 1;
if (checkFileExists(fileName) == FALSE)
{
printf("- Given file does not exists!\n");
return ERROR;
}
else
src = fopen(fileName, "rb");
// create output filename #MUST FREE ALLOCATED MEMORY#
outputFilename = getOutputFilename(fileName, ".p3.ppm");
// REMOVE + AFTER TESTING
dest = fopen(outputFilename, "w+");
// check that the input file is actually in P6 format
fscanf(src, "%s", magicNumber);
if (strcmp(magicNumber, "P6") != 0)
return ERROR;
fscanf(src, "\n%d %d\n%d\n", &width, &height, &depth);
fprintf(dest, "P3\n");
fprintf(dest, "#P3 converted from P6\n");
fprintf(dest, "%d %d\n%d\n", width, height, depth);;
for (i = 0; i < width*height; i++)
{
for (j = 0; j < 3; j++)
{
fread(&red, 1, 1, src);
fread(&green, 1, 1, src);
fread(&blue, 1, 1, src);
}
for (j = 0; j < 3; j++)
fprintf(dest, "%d %d %d ", red, green, blue);
if (widthCounter == width)
{
fprintf(dest, "\n");
widthCounter = 1;
}
else
widthCounter++;
}
free(outputFilename);
fclose(src);
fclose(dest);
return TRUE;
}
为什么我会遇到这种质量损失?
编辑:使用记事本打开 GIMP 转换的输出文件时,我发现我的转换器的样本(红绿或蓝色值)是 GIMP 的 3 倍。