I am trying to read all .png files in a folder then get their gray scale and rewrite them in a new folder (with the same name).
my path_in files : 1.png, 2.png, ... (different number of total files everytime)
so by the end, path_out should contains same numbers of png files, all with the same name as in path_in.
But I am now stuck. As I am new to c++, I could not get myself to get this right.
The error is on the overloads '+' operators.
int main()
{
Mat pic,gray;
vector<cv::String> fn;
glob(path_in + "*.png", fn, false);
vector<Mat> images;
size_t count = fn.size();
for (size_t i = 1; i < count + 1; i++)
{
pic = imread(path_in + i, CV_LOAD_IMAGE_COLOR);
cvtColor(pic, gray, CV_BGR2GRAY);
imwrite(path_out + i + ".png", gray);
}
}
Edited code:
#include "stdafx.h"
#include "iostream"
#include <direct.h>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
std::string path_in("C:/Users/t/");
std::string path_out("C:/Users/New folder/");
int main()
{
_mkdir(path_out.c_str()); //create folder if does not exist
Mat pic, gray;
vector<cv::String> fn;
glob(path_in + "*.png", fn, false);
//vector<Mat> images;
size_t count = fn.size();
for (size_t i = 1; i < count; ++i)
{
pic = imread(path_in + fn[i], CV_LOAD_IMAGE_COLOR);
cvtColor(pic, gray, CV_BGR2GRAY); //error : Unhandled exception
imwrite(path_out + fn[i] + ".png", gray);
}
waitKey(0);
return 0;
}
**apologize for not showing the complete code at the beginning, here is the combination code of mine with the suggested answer.
can anyone shed some lights?
Assuming path_in
and path_out
are std::string
or cv::String
variables, you can't use the +
operator to append size_t
values as-is to them, you have to convert the integer values to std::string
/cv::String
values first, eg:
int main()
{
Mat pic, gray;
vector<cv::String> fn;
glob(path_in + "*.png", fn, false);
size_t count = fn.size();
for (size_t i = 1; i <= count; ++i)
{
pic = imread(path_in + std::to_string(i) + ".png", CV_LOAD_IMAGE_COLOR);
cvtColor(pic, gray, CV_BGR2GRAY);
imwrite(path_out + std::to_string(i) + ".png", gray);
}
return 0;
}
However, you shouldn't assume the filenames are sequentially numbered. glob()
returns a vector
of strings, so presumably it returns the actual filenames, so use them as-is instead, eg:
int main()
{
Mat pic, gray;
vector<cv::String> fn;
glob(path_in + "*.png", fn, false);
size_t count = fn.size();
for (size_t i = 0; i < count; ++i)
{
pic = imread(path_in + fn[i], CV_LOAD_IMAGE_COLOR);
cvtColor(pic, gray, CV_BGR2GRAY);
imwrite(path_out + fn[i], gray);
}
return 0;
}