如何在OpenCV 2.4.3中保存(cvWrite或imwrite)图像?

时间:2013-04-17 20:15:17

标签: opencv face-detection save-image

我正在尝试将OpenCV图像保存到硬盘驱动器。

以下是我的尝试:

public void SaveImage (Mat mat) {
  Mat mIntermediateMat = new Mat();

  Imgproc.cvtColor(mRgba, mIntermediateMat, Imgproc.COLOR_RGBA2BGR, 3);

  File path =
    Environment.getExternalStoragePublicDirectory(
    Environment.DIRECTORY_PICTURES);
  String filename = "barry.png";
  File file = new File(path, filename);

  Boolean bool = null;
  filename = file.toString();
  bool = Highgui.imwrite(filename, mIntermediateMat);

  if (bool == true)
    Log.d(TAG, "SUCCESS writing image to external storage");
    else
    Log.d(TAG, "Fail writing image to external storage");
  }
}

任何人都可以展示如何使用OpenCV 2.4.3保存该图像吗?

1 个答案:

答案 0 :(得分:5)

您的问题有点令人困惑,因为您的问题是关于桌面上的OpenCV,但您的代码是针对Android的,并且您询问IplImage,但您发布的代码是使用C ++和Mat。假设您使用C ++在桌面上,您可以执行以下操作:

cv::Mat image;
std::string image_path;
//load/generate your image and set your output file path/name
//...

//write your Mat to disk as an image
cv::imwrite(image_path, image);

......或者更完整的例子:

void SaveImage(cv::Mat mat)
{
    cv::Mat img;     
    cv::cvtColor(...); //not sure where the variables in your example come from
    std::string store_path("..."); //put your output path here       

    bool write_success = cv::imwrite(store_path, img);
    //do your logging... 
}

根据提供的文件名选择图像格式,例如如果你的store_path字符串是“output_image.png”,那么imwrite将保存它是一个PNG图像。您可以在the OpenCV docs找到有效扩展程序列表。

使用OpenCV将图像写入磁盘时要注意的一点是,根据Mat类型,缩放会有所不同;也就是说,对于浮点数,图像应该在[0,1]范围内,而对于无符号字符,它们将来自[0,256]。

对于IplImages,我建议只使用Mat,因为旧的C接口已被弃用。您可以通过cvarrToMat将IplImage转换为Mat,然后使用Mat,例如

IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);
//now can use cv::imwrite with newC

或者,您可以使用

将IplImage转换为Mat
Mat newC(oldC0); //where newC is a Mat and oldC0 is your IplImage

此外,我刚刚在OpenCV网站上注意到this tutorial,它为您提供了在(桌面)环境中加载和保存图像的步骤。