I am trying to load an Gdiplus bitmap of 8 bit depth to an opencv mat. the image is in greyscale.
Greyscale Image of 8bit:
.
this is the VC++ code snippet I am using to convert it into cv::mat. But using this when I convert I am getting a faded image of the original image in the cv::mat. What could be the reason?
// Creating the m_Bitmap
Gdiplus::Bitmap bit(152, 152, PixelFormat8bppIndexed);
m_Bitmap = bit.Clone(0, 0, bit.GetWidth(), bit.GetHeight(), PixelFormat8bppIndexed);
// Later Different paths are added to this bitmap
// Converting this bitmap to cv::mat
Gdiplus::PixelFormat format = m_Bitmap->GetPixelFormat();
if (format == PixelFormat8bppIndexed)
{
Gdiplus::BitmapData bitmapData;
Gdiplus::Rect rect(0, 0, width, height);
m_Bitmap->LockBits(&rect, Gdiplus::ImageLockModeRead, format, &bitmapData);
cv::Mat nmat = cv::Mat(height, width, CV_8UC1, static_cast<unsigned char*>(bitmapData.Scan0), bitmapData.Stride).clone();
}
Original bitmap Image (m_Bitmap):

This is the image preview of cv::mat nmat:

I need to have the same image as the source to be loaded into the cv::mat but that is not happening here.
Note: When the bitmap was in PixelFormat32bppARGB
The below approach has made the correct conversion and the data in the cv::mat was proper. (like there was no fading thing)
// Lock the gdiplus::bitmap object to get direct access to the pixel data
Gdiplus::BitmapData bitmapData;
Gdiplus::Rect rect(0, 0, width, height);
m_Bitmap->LockBits(&rect, Gdiplus::ImageLockModeRead, format, &bitmapData);
// Create a cv::Mat object with the same dimensions and type as the gdiplus::bitmap object
cv::Mat nmat = cv::Mat(height, width, CV_8UC4, static_cast<unsigned char*>(bitmapData.Scan0), bitmapData.Stride).clone();
// Convert to single channel image for performing open::CV operations
cv::Mat singleChannelImage;
cv::cvtColor(nmat, singleChannelImage, cv::COLOR_RGBA2GRAY);
m_Bitmap->UnlockBits(&bitmapData);

nmatactually has "faded" pixels (and it's not misrepresentation in the debug preview display) ? you can usecv::imwriteto save to file and check.PixelFormat24bppRGBbyLockBits. [2] Create from this data cv::Mat. [3] Usecv::cvtColorto convert 3 channels image into one - grayscale.