【发布时间】:2019-03-25 23:01:58
【问题描述】:
我正在尝试计算 PPM 图像的平均 RGB 值。我的尝试可以在下面的代码中看到,但是当我运行解决方案时,cmd 中的输出是:0 0 0
我觉得我尝试int clr = fscanf(f, "%i %i %i", &x, &y, &z); 中的代码行也不正确——我尝试使用 fscanf 作为 getPixel() 的替代品,它使用(显然)过时的“graphics.h”标头。
总结一下:
1.如何计算和打印 PPM 文件的平均 RGB 值?
#include <stdio.h>
#include <stdlib.h>
//Image size
#define WIDTH 2048
#define HEIGHT 2048
int main()
{
int x, y, z;
//Used for tally
int R = 0;
int G = 0;
int B = 0;
//Loop count value
int total = 0;
//File handle
FILE *f;
//File open
f = fopen("Dog2048x2048.ppm", "r");
if (f == NULL)
{
fprintf(stderr, "Error: file could not be opened");
exit(1);
}
//Iterate through the image width and height
for (int i = 0; i < WIDTH; i++)
{
for (int j = 0; j < HEIGHT; j++)
{
//Color clr = bmp.GetPixel(x, y);
int clr = fscanf(f, "%i %i %i", &x, &y, &z);
R += clr;
G += clr;
B += clr;
total++;
}
}
//Calculate average
R /= total;
G /= total;
B /= total;
//Print RGB
printf("%i %i %i", R, G, B);
return 0;
}
【问题讨论】:
-
您没有考虑文件的标题部分(其中包括图像的宽度和高度等内容......您不应该对这些值进行硬编码。)
-
并查找
fscanf()的文档以查看它返回的内容。然后想想你是如何使用这个价值的...... -
我认为它是 ascii P3 格式 PPM,因为您使用的是
fscanf(),但您可能需要检查以确认在读取 P6 上的标题和错误时(或者也读取该格式)。如果是 P3,并且图像中有 cmets,则在读取文件时也必须考虑这些因素。 -
R += x; G += y, etc.最好每次向 R、G 和 B 添加 3,如果 scanf 失败,则最糟糕的是添加 0。假设您有一个完整的 P3 文本 PPM 文件,您也没有考虑标题等。 -
注意:
2048x2048,R可以高达 50%INT_MAX。如果文件可以变得更大,请考虑long long R = 0;。