我正试图在我的Mac上从OpenCV保存一张图片,我正在使用以下代码,但到目前为止它还没有工作。
cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage);
有人能看出为什么这可能没有保存吗?
OpenCV有时在保存JPG
图像方面存在问题,尝试改为保存为BMP
格式:
cv::imwrite("/Users/nickporter/Desktop/Gray_Image.bmp", cvImage);
在此之前,请确保您的图像cvImage
是有效的。您可以通过先显示图像来检查它:
在此之前,请确保您的图像cvImage
是有效的。您可以通过先显示图像来检查它:
namedWindow("image", WINDOW_AUTOSIZE);
imshow("image", cvImage);
waitKey(30);
.bmp
,神奇地就开始工作了。OpenCV 3.4 facepalm - user189198"C:\\folder1\\folder2\\"
,但实际上当folder2
不存在时,复制操作就会失败(这是我的实际测试结果,不是官方公告)。我通过检查文件夹是否存在并在不存在时创建一个文件夹来解决了这个问题。以下是一些代码,希望能帮助使用c++和boost::filesystem。#include <boost/filesystem.hpp>
#include <iostream>
std::string str_target="C:\\folder1\\folder2\\img.jpg";
boost::filesystem::path path_target(str_target);
boost::filesystem::path path_folder=path_target.parent_path();//extract folder
if(!boost::filesystem::exists(path_folder)) //create folder if it doesn't exist
{
boost::filesystem::create_directory(path_folder);
}
cv::imwrite(str_target,input_img);
我刚遇到了类似的问题,尝试加载 jpg 文件并将其保存为 jpg。添加了这段代码后,现在看起来已经没问题了。
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);
cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage, compression_params);
cv::Mat cvImage;
#ifdef DEBUG
IplImage image = IplImage(cvImage);
cvSaveImage("filename.jpg", &image);
#else
cv::imwrite("filename.jpg", cvImage);
#endif
image
和一个filename
。在函数中,指定您希望写入的路径,并具有执行此操作的权限。void imageWrite(const cv::Mat &image, const std::string filename)
{
// Support for writing JPG
vector<int> compression_params;
compression_params.push_back( CV_IMWRITE_JPEG_QUALITY );
compression_params.push_back( 100 );
// This writes to the specified path
std::string path = "/path/you/provide/" + filename + ".jpg";
cv::imwrite(path, image, compression_params);
}
虽然这不适用于您的情况,但如果传递给cv::imwrite函数的图像路径超过了系统允许的最大路径长度(或可能允许的文件名长度),则可能会出现此问题。
对于Windows,请参见:https://www.quora.com/What-is-the-maximum-character-limit-for-file-names-in-windows-10
cvImage
以查看图像是否正确。 - feihuimshow
能够显示cvImage
吗? - feihuimshow
,但是出现了一个很长的异常。请查看我的问题:http://answers.opencv.org/question/29895/imshow-throwing-exception-osx/ - user2780240cvShowImage
怎么样?你可以编写一个简单的C程序来测试load
和cvShowImage
。 - feihu