Apply transformation matrix to pixels in OpenCV image

I want to change the color basis of the image from RGB to another. I have an M matrix that I want to apply to each RGB pixel, which we can define as x ij .

I am currently repeating every pixel of a NumPy image and calculating Mx ij manually. I can't even vectorize it line by line, because RGB is 1x3 instead of a 3x1 array.

Is there a better way to do this? Maybe a function in OpenCV or NumPy?

+1
source share
1 answer

It is not possible to remember the canonical way to do this (possibly avoiding transference), but this should work:

import numpy as np

M = np.random.random_sample((3, 3))

rgb = np.random.random_sample((5, 4, 3))

slow_result = np.zeros_like(rgb)
for i in range(rgb.shape[0]):
    for j in range(rgb.shape[1]):
        slow_result[i, j, :] = np.dot(M, rgb[i, j, :])

# faster method
rgb_reshaped = rgb.reshape((rgb.shape[0] * rgb.shape[1], rgb.shape[2]))
result = np.dot(M, rgb_reshaped.T).T.reshape(rgb.shape)

print np.allclose(slow_result, result)

, Scikit Image:

+2

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


All Articles