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...

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
Aayman Khalid
  • 446
  • 3
  • 12
  • 24

5 Answers5

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++;
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
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.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
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

Abhineet
  • 5,320
  • 1
  • 25
  • 43
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 );
berak
  • 39,159
  • 9
  • 91
  • 89
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.
LovaBill
  • 5,107
  • 1
  • 24
  • 32