perr0
perr0

Reputation: 145

Changing cv::Mat with image copied from buffer affects original image

I have image buffer in 24bit RGB format. This buffer is copied to cv::Mat using

cv::Mat mat = cv::Mat(image->height, image->width, CV_8UC3, image->data);

Since this buffer is in RGB format and OpenCV uses BGR format, I'm converting matto BGR with

cv::cvtColor(mat, mat, CV_RGB2BGR);

This works, but when I check original image its channels are inverted as well (and so they become wrong) and I don't want this to happen.

I'd like to invert mat channels order leaving image-data (my image buffer) untouched. How can I do that?

Upvotes: 0

Views: 11468

Answers (1)

Quentin Geissmann
Quentin Geissmann

Reputation: 2240

I presume (I am not certain) that if you use cv::cvtColor(mat, mat, CV_RGB2BGR);, you actually recreate mat, but you overwrite data with the RGB->BGR converted data. Since you pass data to your "mat" using pointer, if you overwrite the data in mat, you change "image->data" as well.

Therefore, I do not expect less performance than:

cv::Mat mat = cv::Mat(image->height, image->width, CV_8UC3, image->data);
cv::Mat mat2;
cv::cvtColor(mat, mat2, CV_RGB2BGR);
//Work with mat 2 now

Rather than overwriting, you write new data. This should bear the same performance cost... I do not know what plan to do with your image after colour conversion, but even if the performance was different, it is likely to have an overall minor impact.

Upvotes: 6

Related Questions