opencv:如何将浮点数组保存为图像

新手上路,请多包涵

我对 c++ 和 opencv 库完全陌生。我正在浏览 stackoverflow 并搜索网络,但找不到我的问题的答案。

如何将浮点数组保存到 C++ 中的图像中?目前(作为练习)我只是手动将图像转换为灰度(尽管我读到这可以用 opencv 完成)。

稍后我计划做一些过滤操作和其他像素操作。这就是我想使用浮点数组(大小为 512*512)的原因。

这是代码。我所知道的是,float 数组必须转换为 int 或 char 或 uint8 或 cv::Mat,以便它可以保存为 .png,但我不知道如何。

非常感谢任何提示或链接。

 #include <stdio.h>
#include <opencv2/highgui/highgui.hpp>

int main(void)
{
  // load in image using opencv and convert to char
  cv::Mat myImg = cv::imread("~/Lenna.png", CV_LOAD_IMAGE_COLOR);
  unsigned char *img = (unsigned char*)(myImg.data); //somehow only works for unsigned char and not for float (SegFault)

  float *r = new float[512*512];
  float *g = new float[512*512];
  float *b = new float[512*512];
  float *gray = new float[512*512];

  // 3*iCol, bc every pixel takes 3 bytes (one for R channel/B channel /G channel).
  // see http://answers.opencv.org/question/2531/image-data-processing-in-cvmat/
  // faster to loop through rows first and then through colums (bc MAT stored in row-major order)
  uint iPix = 0;
  for(int iRow=0; iRow<512 ;iRow++){
    for(int iCol=0; iCol<512 ;iCol++){
      b[iPix] = (float) img[myImg.step * iRow + 3*iCol     ];
      g[iPix] = (float) img[myImg.step * iRow + 3*iCol + 1 ];
      r[iPix] = (float) img[myImg.step * iRow + 3*iCol + 2 ];
      gray[iPix] = (float) 0.0722*b[iPix] + 0.2126*r[iPix] + 0.7152*g[iPix];
      iPix++;
    }
  }

  //write image to file (NOT WORKING!)
  cv::imwrite("~/imgOut.png",  (cv::Mat) gray);
}

原文由 user3524709 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

您可以使用

cv::imwrite("~/imgOut.bmp",  cv::Mat(512, 512, CV_32FC1, gray));

PS: 我将它保存到 BMP 以使其工作,因为对于 imwrite() ,只有 8 位(或 16 位无符号( CV_16U )在 PNG、JPEG 2000 的情况下,和 TIFF)单通道或 3 通道(具有“BGR”通道顺序)图像可以使用此功能保存。

原文由 herohuyongtao 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题