【问题标题】:What's wrong with my program to decode an image?我的图像解码程序有什么问题?
【发布时间】:2013-05-28 13:03:06
【问题描述】:

我得到了一个图像文件,而真实图像隐藏在随机像素后面。我必须通过将红色值乘以 10 并将绿色/蓝色值设置为等于新的红色值来解码图像。 (而且我不能超过颜色的最大值 255)当我运行这个程序时,它应该创建一个名为“hidden.ppm”的输出文件。我运行了我的程序,但我得到的只是“分段错误”,我不知道为什么。

void print_pixel(int a)
{
   int r, g, b;

   r = a * 10;
   g = r;
   b = r;

   if (r > 255)
   {
      r = 255;
   }

   if (g > 255)
   {
      g = 255;
   }

   if (b > 255);
   {
      b = 255;
   }

   printf("%d\n", r);
   printf("%d\n", g);
   printf("%d\n", b);
}

void decode(int arg_list, char *in[])
{
   FILE *input, *output;
   int check, value;

   fprintf(output, "P3\n");
   fprintf(output, "%d %d\n", 1024, 768);
   fprintf(output, "255\n");

   input = fopen(in[1], "r");
   output = fopen("hidden.ppm", "w");

   check = fscanf(input, "%d\n", &value);

   while (check != EOF)
   {
      print_pixel(value);
   }
}

int main(int argc, char *argv[])
{
   if (argc == 0)
   {
      printf("usage: a.out <input file>\n");
      return 1;
   }

   decode(argc, argv);
}

【问题讨论】:

  • 那是实际的代码吗?因为它是一个无限循环
  • 这是代码,我将如何纠正无限循环?当它到达输入文件的末尾时它不会停止吗?

标签: c image pixel decode ppm


【解决方案1】:
  1. 你在fopen之前使用output

  2. 您的 while 循环是无限的,因为您只执行一次 check = fscanf(input, "%d\n", &amp;value);。您可能的意思是:

    do{
        check = fscanf(input, "%d\n", &value);
        print_pixel(value);
    while(check != EOF);
    

【讨论】:

  • 哦!所以 check=... 和 print_pixel 都进入了 while 循环? (因为我只执行了一次 check=... )对不起,我没有看到: do{ 之前的符号,这是否意味着在 while 循环中执行?还是以前?谢谢!
  • 另外,我想知道我的 print_pixel 函数是否有问题。因为,我想将它打印到输出文件,所以我必须使用 fprintf 而不是 printf 吗? (我试过这样做,但这意味着我需要“输出”作为 fprintf 的第一个参数,并且直到 print_pixel 函数之后我才声明“输出”)
  • 你可以将output作为参数传递给print_pixelvoid print_pixel(FILE * output, int a){ ...
  • 感谢所有提示/帮助家伙! :)
【解决方案2】:

在您的decode 实现中,您在初始化输出流之前访问它。将输出文件的开头移到fprintf 的上方。

void decode(int arg_list, char *in[])
{
   FILE *input, *output;
   int check, value;

   input = fopen(in[1], "r");
   output = fopen("hidden.ppm", "w");

   fprintf(output, "P3\n");
 [...]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多