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

给定一幅PGM格式的图像,任务是反转PGM格式的图像颜色(制作负片)。 先决条件: c-program-to-write-an-image-in-pgm格式 PGM图像表示灰度图形图像。PGM是便携式灰色地图的缩写。此图像文件包含一个或多个PGM图像文件。 数据块的重要性: 用于创建PGM图像的数据如下所示:

null
  • P2是灰色图像的类型
  • 4是图像维度
  • 255是最大灰度
  • 因为,图像数据以矩阵格式存储,每行表示图像行,值表示对应像素的灰度。最大值(255)用于白色,最小值(0)用于黑色。

例子:

P24 4255255 0   255 00   255 0   255100 200 150 10050  150 200 0

输入图像如下所示:

pgm image

如何反转图像数据? 反转灰度图像意味着使用(255–灰度)更改图像的灰度,即如果像素的灰度为150,则负片图像的灰度为(255–150)=105。这意味着255将随0而变化,0将随255而变化。它是灰色中黑白比例的变化。 例子:

P24 42550   255 0   255255 0   255 0155 55  105 155205  105 55 255

输出图像如下所示:

invert image

C

#include<stdio.h>
#include<process.h>
#include<stdlib.h>
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 %d %d 255 ", width, height);
fprintf (negative_pgmfile, "P2 %d %d 255 ", 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, "");
}
// 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, "");
}
fclose (pgmfile);
fclose (negative_pgmfile);
}


输出: 原始图像

pgm image

负片(反转)图像

invert image

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享