Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

python - Apply transformation matrix to pixels in OpenCV image

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...