Convert Mat to TBitmap and TBitmap to Mat C++ Builder 12.2

Hello !

I have only recently started working with OpenCV.

How to make the conversion in the fastest way so that there is a minimum delay for conversion:

  1. Mat to TBitmap ?
  2. TBitmap to Mat ?
Graphics::TBitmap* BMP_TEST = new Graphics::TBitmap();
Mat frame;

void __fastcall TfrmMain::MatToBitmap(const cv::Mat &frame , TBitmap *bmp)
{
if (frame.empty()) return;

cv::Mat converted;

if (frame.type() == CV_8UC3) {
	cv::cvtColor(frame, converted, cv::COLOR_RGB2BGR);
}
else if (frame.type() == CV_8UC1) {
	cv::cvtColor(frame, converted, cv::COLOR_GRAY2BGR);
}
else if (frame.type() == CV_8UC4) {
	cv::cvtColor(frame, converted, cv::COLOR_BGRA2BGR);
}
else if (frame.type() == CV_16UC1) {
	frame.convertTo(converted, CV_8U, 255.0/65535.0);
	cv::cvtColor(converted, converted, cv::COLOR_GRAY2BGR);
}
else if (frame.type() == CV_16UC3) {
	frame.convertTo(converted, CV_8U, 255.0/65535.0);
}
else if (frame.type() == CV_32FC1) {
	frame.convertTo(converted, CV_8U, 255.0);
	cv::cvtColor(converted, converted, cv::COLOR_GRAY2BGR);
}
else if (frame.type() == CV_32FC3) {
	frame.convertTo(converted, CV_8U, 255.0);
}
else if (frame.type() == CV_8UC3 && !frame.empty()) {
	cv::cvtColor(frame, converted, cv::COLOR_RGB2BGR);
}
else {
	converted = frame.clone();
}

bmp->PixelFormat = pf24bit;
bmp->Height = converted.rows;
bmp->Width  = converted.cols;

for (int y = 0; y < converted.rows; y++) {
	const unsigned char* src = converted.ptr<unsigned char>(y);
	unsigned char* dst = static_cast<unsigned char*>(bmp->ScanLine[y]);

	for (int x = 0; x < converted.cols; x++) {
		dst[x * 3 + 0] = src[x * 3 + 2];  // R <- B
		dst[x * 3 + 1] = src[x * 3 + 1];  // G <- G
		dst[x * 3 + 2] = src[x * 3 + 0];  // B <- R
	}
}

}

1 Like
**iamcybertic**
void __fastcall TfrmMain::MatToBitmap(const cv::Mat &frame , TBitmap *bmp)

Thank you very much!!! :+1:

Can you give an example with a reverse BitmapToMat transformation?