BMP图象(灰度图)转化为二维数组的C语言实现(bmp2array)

这段C语言代码实现了将BMP灰度图像转换为二维字符数组。通过读取BMP文件并解析其头部信息,将像素值写入输出文件,最终得到一个表示图像数据的二维数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下代码可以实现BMP灰度图到二维数组的转换
#include <stdio.h>
#define get ch=getc(in) 
#define getdw ch=getc(in);ch=getc(in);ch=getc(in);ch=getc(in) 
int chabiao(FILE *fp,unsigned char color);
int main(int argc, char *argv[]) 

FILE * in ,*out; 
int j,l,k,a,cout,length,width,Alength,offset,ofs;
unsigned long i,filesize;
unsigned char ch,infile[10],outfile[]="$tmp.txt",flip[800];
unsigned char temp,tempR,tempG,tempB,newtemp;
//unsigned int ch;
printf("input bmp filename:"); 
scanf("%s",infile); 
if((in=fopen(infile,"rb"))==NULL) 

printf("can't open "); 
exit(0); 

if((out=fopen(outfile,"w"))==NULL) 

printf("cann't open"); 
exit(0); 
}&

### 将灰度图 BMP 文件读取到 C++ 中的二维数组 为了实现这一目标,可以利用 OpenCV 库来简化图像处理流程。以下是具体方法: #### 使用 OpenCV 读取图像并换为二维数组 OpenCV 提供了一个强大的接口用于图像操作。通过 `imread` 函数可以从磁盘加载图像,并将其作为矩阵对象返回。对于灰度图像而言,该函数会自动将彩色通道压缩成单个亮度值。 ```cpp #include <opencv2/opencv.hpp> using namespace cv; // 定义全局变量表示图像的高度和宽度 const int Height = 480; const int Width = 640; int main() { // 加载灰度模式下的测试图片 Mat image_gray = imread("./test.bmp", IMREAD_GRAYSCALE); if (image_gray.empty()) { printf("Could not open or find the image\n"); return -1; } // 创建一个unsigned char类型的二维数组用来保存灰度值 unsigned char img_gray[Height][Width]; // 自定义函数Mat2array完成从cv::Mat至二维数组之间的换 void Mat2array(const Mat& mat, unsigned char array[][Width], int height, int width); // 调用自定义函数进行实际的数据复制工作 Mat2array(image_gray, img_gray, Height, Width); // 显示原始图像以便验证正确性 imshow("Gray Image", image_gray); waitKey(0); return 0; } ``` 上述代码展示了如何使用 OpenCV 的 `imread()` 方法读入一幅灰度图像,并创建了一个名为 `img_gray` 的二维字符型数组来容纳这些像素数据[^2]。 接下来是一个辅助性的成员函数原型声明及其简单的逻辑框架,它负责执行由 `cv::Mat` 至标准 C/C++ 数组间的映射关系建立: ```cpp void Mat2array(const Mat& mat, unsigned char array[][Width], int height, int width){ for(int i=0;i<height;++i){ for(int j=0;j<width;++j){ array[i][j]=mat.at<unsigned char>(i,j); } } } ``` 这段代码实现了遍历整个输入矩阵并将每个元素赋给对应的二维数组位置的操作。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值