版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengxianghui01/article/details/84928189
实现3*3滤波,代码没有对边界处理:
#include <Windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(int argc, char** argv)
{
FILE *fp = fopen("./01.bmp", "rb");
if (fp == 0)
return 0;
BITMAPFILEHEADER fileHead;
fread(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
BITMAPINFOHEADER infoHead;
fread(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);
int width = infoHead.biWidth;
int height = infoHead.biHeight;
int biCount = infoHead.biBitCount;
RGBQUAD *pColorTable;
int pColorTableSize = 0;
pColorTable = new RGBQUAD[256];
fread(pColorTable, sizeof(RGBQUAD), 256, fp);
pColorTableSize = 1024;
unsigned char *pBmpBuf;
int lineByte = (width*biCount / 8 + 3) / 4 * 4;
pBmpBuf = new unsigned char[lineByte*height];
fread(pBmpBuf, lineByte*height, 1, fp);
fclose(fp);
// 平滑滤波
unsigned char*pBmpBuf1;
pBmpBuf1 = new unsigned char[lineByte*height];
for (int i = 0; i < height; ++i){
for (int j = 0; j < width; ++j){
unsigned char *p;
p = (unsigned char *)(pBmpBuf1 + lineByte*i + j);
(*p) = 255;
}
}
// 滤波处理
int sum, m, n;
for (int i = 1; i < height-1; ++i){
for (int j = 1; j < width-1; ++j){
unsigned char *p1, *p2;
sum = 0;
p1 = (unsigned char *)(pBmpBuf + i*lineByte + j);
p2 = (unsigned char *)(pBmpBuf1 + i*lineByte + j);
for (m = i-1; m <= i+1; ++m){
for (n = j-1; n <= j+1; ++n){
sum += *(p1 + (m-i)*lineByte + (n-j));
}
}
(*p2) = round(sum / 9.0);
}
}
// 写入文件
FILE *fpo = fopen("./smoothing.bmp", "wb");
if (fpo == 0)
return 0;
BITMAPFILEHEADER dstFileHead;
dstFileHead.bfOffBits = 14 + 40 + pColorTableSize;
dstFileHead.bfReserved1 = 0;
dstFileHead.bfReserved2 = 0;
dstFileHead.bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+pColorTableSize + lineByte*height;
dstFileHead.bfType = 0x4D42;
fwrite(&dstFileHead, sizeof(dstFileHead), 1, fpo);
BITMAPINFOHEADER dstInfoHead;
dstInfoHead.biBitCount = biCount;
dstInfoHead.biClrImportant = 0;
dstInfoHead.biClrUsed = 0;
dstInfoHead.biCompression = 0;
dstInfoHead.biHeight = height;
dstInfoHead.biPlanes = 1;
dstInfoHead.biSize = 40;
dstInfoHead.biSizeImage = lineByte*height;
dstInfoHead.biWidth = width;
dstInfoHead.biXPelsPerMeter = 0;
dstInfoHead.biYPelsPerMeter = 0;
fwrite(&dstInfoHead, sizeof(BITMAPINFOHEADER), 1, fpo);
fwrite(pColorTable, sizeof(RGBQUAD), 256, fpo);
fwrite(pBmpBuf1, lineByte*height, 1, fp);
fclose(fpo);
system("pause");
return 0;
}
实验结果:
原图 滤波结果图
实验结果分析:可看到滤波后图像较模糊,且边界有白色边框,原因是将图像初始化为255,即白色,随后在处理的时候没有对边界处理。
后续持续更新用C语言实现图像处理算法,敬请期待,欢迎关注。