Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

1st of all I think your struct is wrong because r,g,b should be uchar...

Now, suppose you have this data:

const int width = 1920, height = 1080;
struct srcPixelType { uchar r, g, b, pad; };
srcPixelType data[width *height];

you could use CV_8UC4 such as for BGR+Alpha images and ignoring Alpha channel...

Size sz(width, height);
cv::Mat mat(sz, CV_8UC4, data);

You can access this data using OpenCV Vec4b data type

Vec4b pxFromOCV;
pxFromBGRA = mat.at<Vec4b>(row, col);
uchar red = pxFromBGRA[0];

Even if you can ignore the 4th channel, OpenCV functions will not. Channels are processed independently wasting time for the useless 4th chan.

In addiction OpenCV functions like imshow, imwrite or VideoWriter expect a BGR image and not RGBx image, than you have to swap B<->R channels before to use these functions.

//colors are wrong because mat is RGBx but BGRx is expected
imshow("the data", mat);
// convert the mat before to show it
Mat img;
cvtColor(mat, img, CV_RGBA2BGR);
imshow("the image from data", img);

because you have to convert your Mat at the end I would suggest to convert it immediately so you will work on less memory:

Size sz(width, height);
cv::Mat mat(sz, CV_8UC4, data);
Mat img;
cvtColor(mat, img, CV_RGBA2BGR);
Vec3b pxFromBGR;
pxFromBGR = img.at<Vec3b>(row, col);
uchar red = pxFromBGRA[2];

1st of all I think your struct is wrong because r,g,b should be uchar...

Now, suppose you have this data:

const int width = 1920, height = 1080;
struct srcPixelType { uchar r, g, b, pad; };
srcPixelType data[width *height];

you could use CV_8UC4 such as for BGR+Alpha images and ignoring Alpha channel...

Size sz(width, height);
cv::Mat mat(sz, CV_8UC4, data);

You can access this data using OpenCV Vec4b cv::Vec4b data type

Vec4b pxFromOCV;
pxFromBGRA = mat.at<Vec4b>(row, col);
uchar red = pxFromBGRA[0];

Even if you can ignore the 4th channel, OpenCV functions will not. Channels are processed independently wasting time for the useless 4th chan.

In addiction OpenCV functions like imshow, imwrite or VideoWriter expect a BGR image and not RGBx image, than you have to swap B<->R channels before to use these functions.

//colors are wrong because mat is RGBx but BGRx is expected
imshow("the data", mat);
// convert the mat before to show it
Mat img;
cvtColor(mat, img, CV_RGBA2BGR);
imshow("the image from data", img);

because you have to convert your Mat at the end I would suggest to convert it immediately so you will work on less memory:

Size sz(width, height);
cv::Mat mat(sz, CV_8UC4, data);
Mat img;
cvtColor(mat, img, CV_RGBA2BGR);
Vec3b pxFromBGR;
pxFromBGR = img.at<Vec3b>(row, col);
uchar red = pxFromBGRA[2];