How can I convert an image into a 1d vector in c++?
Hello everyone, I'm new to OpenCV , please bare with me.
I am trying to train my network with different images (gray scaled) and for that I need to feed it using vectors of float values. (vector<float>).
I searched and downloaded a database of images that were of type pgm
and I need to load them as vectors.
I searched and came up with this code:
cv::Mat mat;
mat = cv::imread(fileName.toStdString().c_str());
cv::imshow(fileName.toStdString().c_str(),mat);
std::vector<float> array;
array.assign((float*)mat.datastart, (float*)mat.dataend);
The image dimensions are 19*19 (19 rows and 19 columns, verified it by rows and cols properties of mat), so the vector size should be 361, but it is 270! Is what I'm doing wrong here?
you probably want to convert to grayscale, when reading:
cv::imread(fileName, cv::IMREAD_GRAYSCALE)
imread() returns uchar images, you cannot just cast it to float and expect to get the pointer arithm right. also, try to avoid messing with internal datastart,dataend members.
std::vector<float>
? opencv's ml algorithms work on cv::MatMat flat = img.reshape(1,1);
is probably, what you want. maybe you need a convertTo(CV_32F), too.May be like this :
@berak: I created the whole neural networks library, its not vectorized yet and I am experimenting the differences, thats why I am not allowed to use opencvs ml algorithms at the moment. By the way doing :
cv::Mat mat = cv::imread(fileName, cv::IMREAD_GRAYSCALE);
mat.convertTo(mat,CV_32F);
std::vector<float> array(mat.data);
fails as well, complains about the conversion from uchar* to const std::allocator<_Ty>&.