欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C语言实现BMP图像边缘检测处理

程序员文章站 2022-03-20 13:45:32
本文实例为大家分享了c语言实现bmp图像边缘检测处理的具体代码,供大家参考,具体内容如下以sobel算子为例,其余模板算子卷积代码部分同sobel算子。如:高斯算子、拉普拉斯算子等#include &...

本文实例为大家分享了c语言实现bmp图像边缘检测处理的具体代码,供大家参考,具体内容如下

以sobel算子为例,其余模板算子卷积代码部分同sobel算子。如:高斯算子、拉普拉斯算子等

#include <stdio.h>
#include <stdlib.h>
#include <windows.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;
 
 int linebyte = (bicount*width / 8 + 3) / 4 * 4;
 rgbquad* pcolortable;
 pcolortable = new rgbquad[256];
 fread(pcolortable, sizeof(rgbquad), 256, fp);
 
 unsigned char* pbmpbuf;
 pbmpbuf = new unsigned char[linebyte*height];
 fread(pbmpbuf, linebyte*height, 1, fp);
 fclose(fp);
 
 // 新图
 file* fop = fopen("sobel.bmp", "wb");
 if (fop == 0)
  return 0;
 unsigned char *pbmpbuf2;
 // 初始化
 pbmpbuf2 = new unsigned char[linebyte*height];
 for (int i = 0; i < height; ++i){
  for (int j = 0; j < width; ++j){
   *(pbmpbuf2 + i*linebyte + j) = *(pbmpbuf + i*linebyte + j);
  }
 }
 
 
 int ul, uc, ur, dl, dc, dr;
 int lu, lc, ld, ru, rc, rd;
 double hir, vec;
 for (int i = 1; i < height - 1; ++i){
  for (int j = 1; j < width - 1; ++j){
   // 垂直梯度算子:检测水平边缘
   vec = 0;
   ul = *(pbmpbuf + (i + 1)*linebyte + (j - 1))*(-1);
   uc = *(pbmpbuf + (i + 1)*linebyte + j)*(-2);
   ur = *(pbmpbuf + (i + 1)*linebyte + j)*(-1);
   dl = *(pbmpbuf + (i - 1)*linebyte + (j - 1)) * 1;
   dc = *(pbmpbuf + (i - 1)*linebyte + j) * 2;
   dr = *(pbmpbuf + (i - 1)*linebyte + j) * 1;
   vec = ul + uc + ur + dl + dc + dr;
   // 水平梯度算子:检测垂直边缘
   hir = 0;
   lu = *(pbmpbuf + (i + 1)*linebyte + (j - 1))*(-1);
   lc = *(pbmpbuf + (i - 0)*linebyte + (j - 1))*(-2);
   ld = *(pbmpbuf + (i - 1)*linebyte + (j - 1))*(-1);
   ru = *(pbmpbuf + (i + 1)*linebyte + (j + 1)) * 1;
   rc = *(pbmpbuf + (i - 0)*linebyte + (j + 1)) * 2;
   rd = *(pbmpbuf + (i - 1)*linebyte + (j + 1)) * 1;
   hir = lu + lc + ld + ru + rc + rd;
   *(pbmpbuf2+i*linebyte+j) = round(sqrt(hir*hir + vec*vec));
  }
 }
 
 fwrite(&filehead, sizeof(bitmapfileheader), 1, fop);
 fwrite(&infohead, sizeof(bitmapinfoheader), 1, fop);
 fwrite(pcolortable, sizeof(rgbquad), 256, fop);
 fwrite(pbmpbuf2, linebyte*height, 1, fop);
 fclose(fop);
 
 system("pause");
 return 0;
}

实验结果:

C语言实现BMP图像边缘检测处理

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。