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

opencv: how to save float array as an image

本文关键字:数组 保存 图像 opencv      更新时间:2023-10-16

我对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);
}

在通过cv::imwrite()保存对象之前,需要构造一个cv::Mat对象。

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

注意:在生成的图像中,所有值都将四舍五入到最接近的整数

将其保存为BMP对我的情况没有帮助。我使用了OpenEXR格式。您需要使用.exr扩展名保存文件。

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

gray.convertTo(outputImg, CV_8UC1);