Convert std::vector<double> to Mat and show the image
I have a std::vector<double>
which contains pixel values calculated from somewhere else. Now I want to convert this to a Mat
type and show it. But I faced some problems...only some part of the resulted image looks find and the rest seems to be corrupted. Can you please tell me what am I doing wrong?
Here is my code:
void convertMeanVectorToImageAndShow(cv::Size size, int type
, PedRec::mean_vector *vector
, QString windowName) {
cv::Mat mat;
mat.create(size.height, size.width, type);
int rows = mat.rows;
int cols = mat.cols;
if (mat.isContinuous()) {
cols = rows*cols;
rows = 1;
}
for (int r = 0; r < rows; ++r)
{
uchar *pOutput = mat.ptr<uchar>(r);
for (int c = 0; c < cols; ++c)
{
*pOutput = (uchar)vector->at(c);
++pOutput;
}
}
cv::imshow(windowName.toStdString(), mat);
}
UPDATE Thanks to @theodore , now I at least get a non-corrupted image.
uchar pv[vector->size()];
for(unsigned int i = 0; i < vector->size(); i++) {
pv[i] = (uchar) vector->at(i);
}
cv::Mat out(size, CV_8UC1);
memcpy(out.data, &pv, vector->size());
cv::imshow(windowName.toStdString(), out);
But it is different than what I expect. In fact what I am doing is getting the mean value of 6000 pedestrian images and the resulted image should at least in theory look like a pedestrian. But this is what I get:
If you compare this with what I had in the begging of my question, this does not look like a pedestrain. the top of the my first image looks like a head and body of a pedestrian. I guess there is something wrong with the type CV_8UC1
? because my original images are pmg GrayScale
. for example:
Type of these images are (int) 16
is it a
vector<double>
as you state in the title orvector<uchar>
as you state in the post?@theodore yes infact it is double but the cast to uchar wouldn't make any difference at the end, right?
well it depends on the values that you have as double.
@theodore Thanks, using your code I get a better looking image. I am pretty sure my double values are between [0, 255]. Can you check my updated question please?
@Sean87 change the line
memcpy(out.data, &pv, vector->size());
tomemcpy(out.data, &pv, vector->size()*sizeof(uchar));