使用C模糊对位图的影响

时间:2014-04-29 15:41:40

标签: c bitmap blur

我在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;
}

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

1 个答案:

答案 0 :(得分:4)

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

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

unsigned char *data;
相关问题