Рассчитать среднее значение RGB для файла PPM - PullRequest
1 голос
/ 26 марта 2019

Я пытаюсь вычислить среднее значение RGB для изображения PPM. Моя попытка может быть замечена в коде ниже, но когда я запускаю решение, вывод в cmd будет: 0 0 0

Мне кажется, что строка кода в моей попытке int clr = fscanf(f, "%i %i %i", &x, &y, &z); также неверна - я пытался использовать fscanf вместо getPixel (), который использует (очевидно) датированный заголовок "graphics.h".

Подведем итог:

1. Как рассчитать и напечатать средние значения RGB для файла PPM?

#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; 
}

Ответы [ 2 ]

1 голос
/ 26 марта 2019

Благодаря помощи каждого пользователя, который прокомментировал / поделился своим решением по этому вопросу, я думаю, что теперь у меня есть решение, которое работает так, как я хочу, как показано ниже.

Код распечатывает файл ppm в указанном ниже формате, а затем переходит к поиску среднего значения RGB файла, который печатается в cmd.

P6 
# ignores comments in header 
width 
height 
max colour value 

Моя попытка рабочего решения каквидно ниже:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    unsigned char r, g, b;
} pixel;

int main(int argc, char* argv[]) {

char magic_number[1];
int w, h, m;
int red = 0; 
int green = 0; 
int blue = 0;
int total = 0;      //Loop count initialised at 0 
FILE* f;            //File handle
pixel currentPix;   //Variable declaration for the current pixel 

//Open and read the PPM file 
f = fopen("Dog2048x2048.ppm", "r");
if (f == NULL) {
    fprintf(stderr, "Error: file cannot be opened");
    exit(1);
}

//Get P6, width, height, maxcolour value 
fscanf(f, "%s %d %d %d", &magic_number, &w, &h, &m);
printf("magic_n = %s, width = %d, height = %d, max_colour = %d\n", magic_number, w, h, m);

//iterate through the height and width of the ppm file 
for (int j = 0; j < h; j++) {
    for (int i = 0; i < w; i++) {

        //Read data from the given stream 
        fread(&currentPix, 3, 1, f);

        //Stores current pixel RGB values in red, green, blue variables
        red += currentPix.r;
        green += currentPix.g;
        blue += currentPix.b;

        //Counts the iterations 
        total++; 
    }
}

//calculate averages for red, green, blue
red /= total;
green /= total;
blue /= total;

//print output of average rgb 
printf("%d, %d, %d", red, green, blue);
getchar();
return 0;
}
1 голос
/ 26 марта 2019

Файл Dog2048x2048.ppm действительно является PPM формата P6, как определено в этом Спецификация формата PPM . Как таковые, его образцы представлены не в виде текста, а в чистом двоичном виде , следовательно, не fscanf(…%i…), а скорее fread() подходит для их чтения, т.е. г. для файла под рукой с Maxval 255:

    // skip over P6\n2048\n2048\n255\n
    if (fscanf(f, "P6 2048 2048%d%*c", &z) < 1)
        puts("unexpected format of file"), exit(1);

    // Iterate through the image width and height 
    for (int i = 0; i < WIDTH; i++)
    {   // Note that you mixed up WIDTH and HEIGHT - just doesn't matter here
        for (int j = 0; j < HEIGHT; j++)
        {
            //Color clr = bmp.GetPixel(x, y);
            unsigned char clr[3];
            if (fread(clr, 3, 1, f) < 1)
                printf("read error at %d,%d\n", i, j), exit(1);

            R += clr[0];
            G += clr[1];
            B += clr[2];
            total++;
        }
    }
...