c++ opencv:如何将浮点数组另存为图像

bxjv4tth  于 2022-11-19  发布在  其他
关注(0)|答案(3)|浏览(293)

我对c和opencv库还是个新手,我浏览了stackoverflow,也搜索了网络,但是没有找到我问题的答案。
如何在c
中将浮点数组保存到图像中?目前(作为练习)我只是手动将图像转换为灰度(尽管我读到这可以用opencv完成)。
稍后我计划做一些过滤器操作和其他像素操作。这就是为什么我想使用一个浮点数组(大小为512*512)。
这是代码,我只知道,浮点数组必须转换成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);
}
nkkqxpd9

nkkqxpd91#

您可以使用

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

**P.S.:**如果您要使用imwrite()将其保存为PNG格式,则仅支持8位或16位无符号。保存为BMP则没有此限制。

gdrx4gfi

gdrx4gfi2#

保存为BMP在我的情况下没有帮助。我使用的是OpenEXR格式。您需要以**.exr**扩展名保存您的文件。

nhaq1z21

nhaq1z213#

您可以在保存之前将图像转换为uint8:

gray.convertTo(outputImg, CV_8UC1);

相关问题