1 | initial version |
I don't know if there is a function of check duplicates and save as another name in OpenCV, so I made it below.
Got checking file existance code from sturkmen above.
It is not very well coded, so modify it with your own taste.
/*
If filename test.jpg exists, it saves same name input as
test(1).jpg, test(2).jpg, ...
*/
const String& imwriteSafe(const String& filename, InputArray img,
const std::vector<int>& params = std::vector<int>()) {
static FILE *f;
static String newname;
f = fopen(filename.c_str(), "rb");
newname = filename;
if (f) {
int counter = 0;
const int extension_dot = filename.find_first_of('.');
String name = filename.substr(0, extension_dot);
String extension = filename.substr(extension_dot);
do{
++counter;
newname = (name + "(" + to_string(counter) + ")" + extension);
fclose(f);
f = fopen(newname.c_str(), "rb");
}while(f);
}
if (cv::imwrite(newname, img, params))
return newname;
else
throw 0;
}
// using example.
int main(){
cv::String filename = "...."
cv::Mat image = ....
// some code here
try {
cv::String writedfilename = imwriteSafe(filename, image);
cout<<"Writed "<<writedfilename<<endl;
}
catch(int e){
cout<<"Writing "<<filename<<"failed."<<endl;
}
}