博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c语言实现灰度图转换为二值图
阅读量:4082 次
发布时间:2019-05-25

本文共 2685 字,大约阅读时间需要 8 分钟。

转载自:

将上篇得到的灰度图转换为二值图,读取像素数据,低于某一值置0,否则设置为255,为得到更好的效果不同图片应采用不同的值

复制代码

1 /*  2 2015年6月2日11:16:22  3 灰度图转换为二值图  4 blog:http://www.cnblogs.com/wd1001/  5 */  6 #include
7 #include
8 #include
9 /* 10 位图头结构 11 */ 12 #pragma pack(1) 13 typedef struct tagBITMAPFILEHEADER 14 { 15 unsigned char bfType[2];//文件格式 16 unsigned long bfSize;//文件大小 17 unsigned short bfReserved1;//保留 18 unsigned short bfReserved2; 19 unsigned long bfOffBits; //DIB数据在文件中的偏移量 20 }fileHeader; 21 #pragma pack() 22 /* 23 位图数据信息结构 24 */ 25 #pragma pack(1) 26 typedef struct tagBITMAPINFOHEADER 27 { 28 unsigned long biSize;//该结构的大小 29 long biWidth;//文件宽度 30 long biHeight;//文件高度 31 unsigned short biPlanes;//平面数 32 unsigned short biBitCount;//颜色位数 33 unsigned long biCompression;//压缩类型 34 unsigned long biSizeImage;//DIB数据区大小 35 long biXPixPerMeter; 36 long biYPixPerMeter; 37 unsigned long biClrUsed;//多少颜色索引表 38 unsigned long biClrImporant;//多少重要颜色 39 }fileInfo; 40 #pragma pack() 41 /* 42 调色板结构 43 */ 44 #pragma pack(1) 45 typedef struct tagRGBQUAD 46 { 47 unsigned char rgbBlue; //蓝色分量亮度 48 unsigned char rgbGreen;//绿色分量亮度 49 unsigned char rgbRed;//红色分量亮度 50 unsigned char rgbReserved; 51 }rgbq; 52 #pragma pack() 53 54 int main() 55 { 56 int i,j; 57 unsigned char ImgData[1000]; 58 FILE * fpGray,* fpBin; 59 fileHeader * fh; 60 fileInfo * fi; 61 rgbq * fq; 62 63 if((fpGray=fopen("G:/vc6.0/work/22.bmp","rb"))==NULL) 64 { 65 printf("打开文件失败"); 66 exit(0); 67 } 68 69 if((fpBin=fopen("G:/vc6.0/work/33.bmp","wb"))==NULL) 70 { 71 printf("创建文件失败"); 72 exit(0); 73 } 74 //读取灰度图数据 75 fh=(fileHeader *)malloc(sizeof(fileHeader)); 76 fi=(fileInfo *)malloc(sizeof(fileInfo)); 77 fq=(rgbq *)malloc(256*sizeof(rgbq)); 78 fread(fh,sizeof(fileHeader),1,fpGray); 79 fread(fi,sizeof(fileInfo),1,fpGray); 80 fread(fq,sizeof(rgbq),256,fpGray); 81 //将头信息写入 82 fwrite(fh,sizeof(fileHeader),1,fpBin); 83 fwrite(fi,sizeof(fileInfo),1,fpBin); 84 fwrite(fq,sizeof(rgbq),256,fpBin); 85 //灰度值低于阈值则置0 86 for(i=0;i<(fi->biHeight);i++) 87 { 88 for(j=0;(j<(fi->biWidth+3)/4*4);j++) 89 { 90 fread(&ImgData[j],1,1,fpGray); 91 if(ImgData[j]>142) 92 ImgData[j]=255; 93 else 94 ImgData[j]=0; 95 } 96 fwrite(ImgData,1,j,fpBin); 97 } 98 free(fh); 99 free(fi);100 free(fq);101 fclose(fpBin);102 fclose(fpGray);103 printf("success\n");104 return 0;105 }

复制代码

结果:

你可能感兴趣的文章
Linux常用统计命令之wc
查看>>
fastcgi_param 详解
查看>>
搞定Java面试中的数据结构问题
查看>>
React Native(一):搭建开发环境、出Hello World
查看>>
mysql 跨机器查询,使用dblink
查看>>
Winform多线程
查看>>
MongoDB数据库插入、更新和删除操作详解
查看>>
MongoDB文档(Document)全局唯一ID的设计思路
查看>>
mongoDB简介
查看>>
Redis持久化存储(AOF与RDB两种模式)
查看>>
memcached工作原理与优化建议
查看>>
Redis与Memcached的区别
查看>>
程序员最核心的竞争力是什么?
查看>>
分布式存储系统设计(1)—— 系统架构
查看>>
MySQL数据库的高可用方案总结
查看>>
环境分支-git版本管理
查看>>
Spring AOP + Redis + 注解实现redis 分布式锁
查看>>
支付宝生活号服务号 用户信息获取 oauth2 登录对接 springboot java
查看>>
CodeForces #196(Div. 2) 337D Book of Evil (树形dp)
查看>>
uva 12260 - Free Goodies (dp,贪心 | 好题)
查看>>