The fastest way to apply a color matrix to an RGB image using OpenCV 3.0?

I have a color image presented as an OpenCV Mat object (C ++, image type CV_32FC3). I have a color correction matrix that I want to apply to each pixel in an RGB color image (or BGR using the OpenCV convention, it doesn't matter here). 3x3 color correction matrix.

I could easily iterate over the pixels and create a v (3x1) vector representing RGB and then calculate M * v, but that would be too slow for my real-time video application.

The cv :: cvtColor function is fast, but apparently does not allow you to customize color conversions. http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

Similar to the following, but I'm using OpenCV for C ++, not Python. Apply transformation matrix to pixels in OpenCV image

+4
source share
2 answers

Mainly related response uses reshapeto convert the mat CV_32FC3size m x nto suit CV_32Fsize (mn) x 3. After that, each row of the matrix contains exactly the color channels of one pixel. Then you can apply regular matrix multiplication to get a new mat and reshapeback to the original form with three channels.

Note. It may be worth noting that the default color space for opencv is BGR, not RGB.

+4

, cv:: reshape. :

#define WIDTH 2048
#define HEIGHT 2048
...

Mat orig_img = Mat(HEIGHT, WIDTH, CV_32FC3);
//put some data in orig_img somehow ...

/*The color matrix
Red:RGB; Green:RGB; Blue:RGB
1.8786   -0.8786    0.0061
-0.2277    1.5779   -0.3313
0.0393   -0.6964    1.6321
*/

float m[3][3] = {{1.6321, -0.6964, 0.0393},
                {-0.3313, 1.5779, -0.2277}, 
                {0.0061, -0.8786, 1.8786 }};
Mat M = Mat(3, 3, CV_32FC1, m).t();

Mat orig_img_linear = orig_img.reshape(1, HEIGHT*WIDTH);
Mat color_matrixed_linear = orig_img_linear*M;
Mat final_color_matrixed = color_matrixed_linear.reshape(3, HEIGHT);

, : - , RGB. float m 1 3, 1 3 OpenGV BGR. . M * v = v_new, M 3x3 v 3x1, v T * M T= v_new T .

+5

Source: https://habr.com/ru/post/1627086/


All Articles