1

I want to change the color basis of an image from RGB to something else. I have a matrix M that I want to apply to each pixel's RGB, which we can define as xij.

I am currently iterating over each pixel of the NumPy image and calculating Mxij manually. I can't even vectorize it over the rows, because the RGB is a 1x3 instead of a 3x1 array.

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

2
  • docs.opencv.org/modules/imgproc/doc/… Commented Feb 27, 2014 at 22:15
  • 1
    @berak I want to do a custom transform, not one of the standard ones with cvtColor Commented Feb 27, 2014 at 22:27

1 Answer 1

2

Can't remember the canonical way to do this (possibly avoiding the transposes) 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) 

If it's a transformation between standard colorspaces then you should use Scikit Image:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.