C#如何将Image列表转换为一维向量并赋值给指定矩阵用于PCA人脸识别
代码实现方案
前置依赖
你需要先引入对应命名空间:
using System.Drawing.Imaging;
核心实现代码
将以下代码替换原代码中//convert the list of images to a one dimension vector注释后的位置即可:
// 先校验训练集数量是否符合要求 if (training.Count != 200) { MessageBox.Show("训练集图像数量不为200张,请检查文件夹路径和过滤规则"); return; } const int ImgWidth = 92; const int ImgHeight = 112; const int VectorLength = ImgWidth * ImgHeight; // 遍历所有训练图像填充矩阵 for (int imgIdx = 0; imgIdx < training.Count; imgIdx++) { using (Bitmap bmp = new Bitmap(training[imgIdx])) { // 锁位图内存批量读取像素,比逐点调用GetPixel效率高100倍以上 BitmapData bmpData = bmp.LockBits( new Rectangle(0, 0, ImgWidth, ImgHeight), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); // 读取像素灰度值到字节数组 int byteSize = bmpData.Stride * ImgHeight; byte[] pixelBuffer = new byte[byteSize]; System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, pixelBuffer, 0, byteSize); bmp.UnlockBits(bmpData); // 填充matrix_data对应行,matrix_data可根据需要选择int/double类型 for (int pixelIdx = 0; pixelIdx < VectorLength; pixelIdx++) { // 灰度图每个像素对应单字节值,范围0-255,可按需做归一化处理 matrix_data[imgIdx, pixelIdx] = pixelBuffer[pixelIdx]; // 如果matrix_data是double类型需要归一化可以改成: // matrix_data[imgIdx, pixelIdx] = pixelBuffer[pixelIdx] / 255.0; } } } // 可选:释放training里的Image对象占用的GDI资源,避免内存泄漏 foreach (var img in training) { img.Dispose(); } training.Clear();
注意事项
- 请确保所有输入的灰度图像素尺寸严格为92*112,否则会出现数据错位或内存越界报错
- 若你的图像不是标准的8位灰度图,需要先做格式转换再读取像素
- 后续做PCA计算前通常需要对所有样本的每个维度做均值中心化,可以在填充矩阵的同时顺便计算均值向量
内容的提问来源于stack exchange,提问作者user16612111
相关产品推荐
相关产品推荐

