📜  C程序以PGM格式反转(负片)图像内容

📅  最后修改于: 2021-05-28 03:10:01             🧑  作者: Mango

给定PGM格式的图像,任务是反转PGM格式的图像颜色(使图像变为负色)。
先决条件: C程序以pgm格式编写图像

PGM图像代表灰度图形图像。 PGM是Portable Gray Map的缩写。该图像文件包含一个或多个PGM图像文件。

数据块的意义:用于创建以下列出的PGM图像的数据:

  • P2是灰色图像类型
  • 4 4是图像尺寸
  • 255是最大灰度
  • 由于图像数据以矩阵格式存储,并且每一行指示图像行,并且值指示对应像素的灰度级。最大值(255)用于白色,最小值(0)用于黑色。

例子:

P2
4 4
255
255 0   255 0
0   255 0   255
100 200 150 100
50  150 200 0

输入图像如下所示:
pgm图片

如何反转图像数据?
反转灰度图像意味着使用(255 –灰色lavel)更改图像的灰度级,即,如果像素的灰度级为150,则负图像的灰度级为(255 – 150)=105。这意味着255将随着0改变。和0将随着255改变。它正在改变以灰色显示的黑白比例。
例子:

P2
4 4
255
0   255 0   255
255 0   255 0
155 55  105 155
205  105 55 255

输出图像如下所示:
反转图像

#include
#include
#include
void main()
{ 
    int i, j, temp = 0;
    int width = 4, height = 4;
      
    // Suppose the 2D Array to be converted to Image 
    // is as given below 
    int img[10][10] = {
        {255, 0, 255, 0},
        {0, 255, 0, 255},
        {100, 200, 150, 100},
        {50, 150, 200, 0}
    };
      
    // file pointer to store image file
    FILE *pgmfile, *negative_pgmfile;
  
    // Open an image file
    pgmfile = fopen("img.pgm", "wb");
      
    // Open an negative image file
    negative_pgmfile = fopen("neg_img.pgm", "wb");
      
    fprintf(pgmfile, "P2 \n %d %d \n 255 \n", width, height);
    fprintf(negative_pgmfile, "P2 \n %d %d \n 255 \n", width, height);
      
    // Create PGM image using pixel value
    for(i = 0; i < height; i++) {
        for(j = 0; j < width; j++)
            fprintf(pgmfile, "%d ", img[i][j]);
        fprintf(pgmfile, "\n");
    }
      
    // Create negative PGM image using pixel value
    for(i = 0; i < height; i++) {
        for(j = 0; j < width; j++) 
            fprintf(negative_pgmfile, "%d ", (255 - img[i][j]));
        fprintf(negative_pgmfile, "\n");
    }
      
    fclose(pgmfile);
    fclose(negative_pgmfile);
}

输出:
原始图片
pgm图片

负(反转)图像
反转图像

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。