Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) ImageToVector

 

Graphics code snippet to convert a VCL TImage to a 2D std::vector. To do the opposite, use VectorToImage.

 

* View the code of 'ImageToVector' in plain text

 

 

#include <cassert>

#include <vector>

#include <vcl.h>

 

//Creates a 2D-std::vector (y-x-ordered) from a TImage

//From http://www.richelbilderbeek.nl/CppImageToVector.htm

const std::vector<std::vector<int> > ImageToVector(const TImage * const image)

{

assert(image!=0 && "Image must not be NULL");

assert(image->Picture->Bitmap!=0 && "Bitmap must not be NULL");

assert(image->Picture->Bitmap->PixelFormat == pf24bit && "Bitmap must be 24 bit");

 

const int width = image->Picture->Bitmap->Width;

const int height = image->Picture->Bitmap->Height;

 

std::vector<std::vector<int> > v(height, std::vector<int>(width));

 

for (int y=0; y!=height; ++y)

{

assert(y >= 0);

assert(y < static_cast<int>(v.size()));

std::vector<int>& vLine = v[y];

const unsigned char * const line

= static_cast<const unsigned char *>(image->Picture->Bitmap->ScanLine[y]);

for (int x=0; x!=width; ++x)

{

assert(x >= 0);

assert(x < static_cast<int>(vLine.size()));

const double grey = static_cast<double>(line[x*3+0] + line[x*3+1] + line[x*3+2])

/ 3.0;

vLine[x] = grey;

assert(grey>=0.0 && grey<256.0);

}

}

return v;

}

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.