Ask Your Question

Is there a way to keep imwrite from overwriting files..?

asked 2015-06-30 07:16:25 -0500

mcsplace gravatar image

Using the latest OpenCV 3.0 on a Linux platform. Using the following to write out image files. However it is more than happy to overwrite an existing file... Is there a mechanism to keep imwrite() from overwriting files...?

/* Create parameters */
vector<int> params;
if( "png" ) == 0 )
    params.push_back( IMWRITE_PNG_COMPRESSION );
    params.push_back( png_compress_level );

/* Try to write image */
    imwrite( filename, *img, params );
catch (runtime_error& ex) 
    fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
    return( 0 );
edit retag flag offensive close merge delete



Yes, you shall do some kind of image name generator, so you'll have a different filename each call of imwrite. For eg: int i=0; std::string savingName = filename + std::to_string(i) + extension;

thdrksdfthmn gravatar imagethdrksdfthmn ( 2015-06-30 08:55:29 -0500 )edit

//to check if the file exist

if (!cvHaveImageReader(filename))
sturkmen gravatar imagesturkmen ( 2015-06-30 09:10:35 -0500 )edit

@sturkmen: but this way, it will not save the image, if it exists...

thdrksdfthmn gravatar imagethdrksdfthmn ( 2015-06-30 09:40:34 -0500 )edit

I am using a name generator for the image filename... Problem is that I forget to move the files after a run.. Then I start up the application again and overwrite my previous run...

I have tried the cvHaveImageReader() and it works as @sturkmen stated above... However, is there any documentation on this function...? I can't find anything.. Thanks,

mcsplace gravatar imagemcsplace ( 2015-06-30 10:10:23 -0500 )edit

@thdrksdfthmn you are right. i only wanted to mention that we can use cvHaveImageReader(filename) to determine if the file exist. int cvHaveImageReader ( const char * filename ) determine can opencv open an image file or not.

sturkmen gravatar imagesturkmen ( 2015-06-30 10:27:35 -0500 )edit

Why C-API???And more, you shall use cvHaveImageWriter, no? There is no doc for it...

thdrksdfthmn gravatar imagethdrksdfthmn ( 2015-07-01 02:35:04 -0500 )edit

3 answers

Sort by ยป oldest newest most voted

answered 2019-12-10 06:49:28 -0500

holger gravatar image

updated 2019-12-10 06:51:01 -0500

Just check if the file exists - problem solved...

edit flag offensive delete link more

answered 2019-12-10 05:37:18 -0500

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);
            newname = (name + "(" + to_string(counter) + ")" + extension);
            f = fopen(newname.c_str(), "rb");

    if (cv::imwrite(newname, img, params))
        return newname;
        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;
edit flag offensive delete link more

answered 2015-07-02 20:35:10 -0500

look a sample code below. for more information you can look here

#include "opencv2/imgcodecs.hpp"
#include <iostream>

using namespace cv;

static bool isFileExist( const String& filename )
    /// Open the file
    FILE* f= fopen( filename.c_str(), "rb" );

    /// in the event of a failure, return false
    if( !f )
        return false;


    return true;

int main(int /*argc*/, char** /*argv*/)
    Mat test = Mat::zeros(100, 100, CV_8UC1);

    String filename = "test.jpg";

    if( !isFileExist(filename))
        imwrite(filename, test);
    else std::cout << filename  << " exist. not saved" << std::endl;

    return 0;
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2015-06-30 07:16:25 -0500

Seen: 8,366 times

Last updated: Dec 10 '19