OpenCV imwrite() not saving image

OpenCV does have problems in saving to JPG images sometimes, try to save to BMP instead:

cv::imwrite("/Users/nickporter/Desktop/Gray_Image.bmp", cvImage);

Also, before this, make sure you image cvImage is valid. You can check it by showing the image first:

namedWindow("image", WINDOW_AUTOSIZE);
imshow("image", cvImage);
waitKey(30);

I met the same problem and one possible reason is that the target folder to place your image. Suppose you want copy A.jpg to folder "C:\\folder1\\folder2\\", but in fact when folder2 doesn't exist, the copy cannot be successful(It is from my actual test, not from official announcement). And I solved this issue by checking whether the folder exists and create one folder if it doesn't exist. Here is some code may it help using c++ & boost::filesystem. May it help.

#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);

Tags:

C++

Opencv