OpenCV imwrite() not saving image
我正在尝试从Mac上的OpenCV中保存图像,并且正在使用以下代码,到目前为止,该代码无法正常工作。
1 | cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage); |
谁能看到为什么这可能无法保存?
OpenCV有时在保存到
1 | cv::imwrite("/Users/nickporter/Desktop/Gray_Image.bmp", cvImage); |
另外,在此之前,请确保图像
1 2 3 | namedWindow("image", WINDOW_AUTOSIZE); imshow("image", cvImage); waitKey(30); |
我遇到了同样的问题,一个可能的原因是放置图像的目标文件夹。假设您要将A.jpg复制到文件夹
1 2 3 4 5 6 7 8 9 10 11 | #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); |
我还建议检查文件夹权限。即使输出文件夹没有写权限,Opencv也会从imwrite静默返回,没有任何异常。
我刚刚遇到了类似的问题,加载了jpg并尝试将其另存为jpg。添加了此代码,现在看起来还不错。
1 2 3 | vector<int> compression_params; compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); compression_params.push_back(100); |
并且您需要在写文件中包含参数。
1 | cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage, compression_params); |
尽管对于您的情况并非如此。如果作为cv :: imwrite函数的参数给出的图像路径超出了系统允许的最大路径长度(或可能允许的文件名长度),则可能会出现此问题。
对于Linux,请参见:https://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs
对于Windows,请参见:https://www.quora.com/What-is-the-maximum-character-limit-for-file-names-in-windows-10
OpenCV 3.2 imwrite()在Windows调试模式下似乎无法写入jpg文件。我使用这种方式而不是imwrite()。
1 2 3 4 5 6 7 8 9 10 11 12 | cv::Mat cvImage; #ifdef DEBUG IplImage image = IplImage(cvImage); cvSaveImage("filename.jpg", &image); #else cv::imwrite("filename.jpg", cvImage); #endif |
可以将以下函数放入您的代码中,以支持写出jpg图像以进行调试。
您只需要传递
1 2 3 4 5 6 7 8 9 10 11 12 | 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); } |