【问题标题】:Blur effect on bitmap using C使用 C 对位图进行模糊效果
【发布时间】:2014-04-29 15:41:39
【问题描述】:

我正在编写在 mp4 上应用模糊滤镜的程序。我正在使用 ffmpeg 从 mp4 中提取 bmp 文件。 但是模糊结果是错误的。图片的某些部分已正确模糊,但其他部分颜色错误。

原图 http://i.imgur.com/XS4yqNd.jpg

图像模糊 http://i.imgur.com/IbcxxA4.jpg

这是读取 bmp、应用模糊和写入 bmp 文件的代码。

int blur(char* input, char *output) {

  //variable dec:
  FILE *fp,*out;
  bitmap_header* hp;
  int n,x,xx,y,yy,ile, avgR,avgB,avgG,B,G,R;
  char *data;
  int blurSize = 5;


  //Open input file:
  fp = fopen(input, "r");
  if(fp==NULL){
    //cleanup
  }

  //Read the input file headers:
  hp=(bitmap_header*)malloc(sizeof(bitmap_header));
  if(hp==NULL)
    return 3;

  n=fread(hp, sizeof(bitmap_header), 1, fp);
  if(n<1){
    //cleanup
  }
  //Read the data of the image:
  data = (char*)malloc(sizeof(char)*hp->bitmapsize);
  if(data==NULL){
    //cleanup
  }

  fseek(fp,sizeof(char)*hp->fileheader.dataoffset,SEEK_SET);
  n=fread(data,sizeof(char),hp->bitmapsize, fp);
  if(n<1){
    //cleanup
  }

for(xx = 0; xx < hp->width; xx++)
{
    for(yy = 0; yy < hp->height; yy++)
    {
        avgB = avgG = avgR = 0;
        ile = 0;

        for(x = xx; x < hp->width && x < xx + blurSize; x++)
        {


            for(y = yy; y < hp->height && y < yy + blurSize; y++)
            {
                avgB += data[x*3 + y*hp->width*3 + 0];
                avgG += data[x*3 + y*hp->width*3 + 1];
                avgR += data[x*3 + y*hp->width*3 + 2];
                ile++;
            }
        }

        avgB = avgB / ile;
        avgG = avgG / ile;
        avgR = avgR / ile;

        data[xx*3 + yy*hp->width*3 + 0] = avgB;
        data[xx*3 + yy*hp->width*3 + 1] = avgG;
        data[xx*3 + yy*hp->width*3 + 2] = avgR;
    }
}

    //Open output file:
  out = fopen(output, "wb");
  if(out==NULL){
    //cleanup
  }

  n=fwrite(hp,sizeof(char),sizeof(bitmap_header),out);
  if(n<1){
    //cleanup
  }
  fseek(out,sizeof(char)*hp->fileheader.dataoffset,SEEK_SET);
  n=fwrite(data,sizeof(char),hp->bitmapsize,out);
  if(n<1){
    //cleanup
  }

  fclose(fp);
  fclose(out);
  free(hp);
  free(data);
  return 0;
}

我不知道问题出在哪里。请帮忙!

【问题讨论】:

  • 打开文件读取时,不应该是二进制模式吗?
  • 看来,您正在修改您读取的同一个位图,因此应用于第一个像素的更改会传播到第二个等。我相信,前几行或几列是可以的,但其余的是变色。
  • 还有一件事,在 BMP 中,当行中的像素数不是 4 的倍数时,会添加额外的填充字节(24 年 4 月 16 日)。在位图上测试您的代码,宽度为 4。
  • 尝试在最小尺寸的位图上重现此行为。
  • @JoachimPileborg 我改成二进制模式,效果一样。

标签: c bitmap blur


【解决方案1】:

在您的平台上,char 似乎是 signed。因此,所有大于127 的颜色值都被解释为负数(256 小于原始值)。这会导致所有奇怪的颜色效果。

要更正它,您可以将data 声明为unsigned char*

unsigned char *data;

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多