4

I am trying to save a sequence of images in visual studio 2008,all with the prefix of "Image". the only differentiating factor should be their number. for example if I am gonna save 10 images then the situation should be

i=1;
while(i<10)
{
cvSaveImage("G:/OpenCV/Results/Imagei.jpg",img2);
i++
//"i" is gonna be different every time
}

so I need to concatenete the integer with the string... looking forward to the answer...

4
  • 2
    Than your question isn't about saving a sequence of images, it's about string manipulation. Commented Mar 11, 2013 at 11:57
  • char name[50]; sprintf(name,"filename%d.jpg", 10); // check also snprintf to print at max 50 characters. Commented Mar 11, 2013 at 11:59
  • @AkiSuihkonen, that's not the C++ way, but post it as an answer so the issue can be resolved. Commented Mar 11, 2013 at 12:00
  • @AkiSuihkonen,this works but the cvSaveImage doesn't seem to be taking array as a path to save image:( Commented Mar 11, 2013 at 12:15

5 Answers 5

5

The c++ way (pre-c++11) would be:

#include <sstream>
...
ostringstream convert;
convert << "G:/OpenCV/Results/Image" << i << ".jpg";
cvSaveImage(convert.str().c_str(), img2);
i++;
Sign up to request clarification or add additional context in comments.

Comments

3

With C++11:

#include <string>

string filename = "G:/OpenCV/Results/Image" + to_string(i) + ".jpg";
cvSaveImage(filename.c_str(), img2);

edit

A generic and possibly more efficient way of building strings is to use a stringstream:

ostringstream ss;

ss << "G:/OpenCV/Results/Image" << i << ".jpg";

string filename = ss.str();
cvSaveImage(filename.c_str(), img2);

This also works with pre-C++11 compilers.

Comments

1

First of all, if you start with i = 10 and do while( i < 10 ), then your code will save only 9 items. Now to your question,

for( i = 1; i < 11; i++ )
{
  std::stringstream imagenum;
  imagenum << "G:/OpenCV/Results/Image" << i << ".jpg" ;
  cvSaveImage(imagenum.str().c_str(), img2) ;
}

Check example_link

Comments

1

opencv comes with cv::format() [which is probably just a sprintf wrapper, but quite handy, imho]

so, your example could look like:

cv::imwrite( cv::format( "G:/OpenCV/Results/Image%d.jpg", i ), img );

or, if you insist on using the outdated 1.0 api, :

cvSaveImage( cv::format( "G:/OpenCV/Results/Image%d.jpg", i ).c_str(), img );

Comments

0
string imgname="./Image_";
char cbuff[20];
sprintf (cbuff, "%03d", i);
imgname.append(cbuff);
imgname.append(".jpg");

Output:

./Image_001.jpg
./Image_002.jpg
./Image_010.jpg etc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.