Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- def xyz2rgb(xyz, white_point='D50'):
- # Normalize XYZ if not already normalized
- xyz = np.array(xyz, dtype=np.float32) # Ensure the array is in float
- xyz /= np.max(xyz)
- if white_point == 'D65':
- # White point adaptation matrix from D65 to D50 using Bradford transformation
- M_D65_to_D50 = np.array([
- [ 0.9555766, -0.0230393, 0.0631636],
- [-0.0282895, 1.0099416, 0.0210077],
- [ 0.0122982, -0.0204830, 1.3299098]
- ])
- # Reshape xyz to (n, 3) for matrix multiplication
- xyz_flat = xyz.reshape(-1, 3)
- # Apply the white point adaptation
- xyz_d50_flat = np.dot(xyz_flat, M_D65_to_D50.T)
- # Reshape back to original shape
- xyz_d50 = xyz_d50_flat.reshape(xyz.shape)
- else:
- # No adaptation needed if already in D50
- xyz_d50 = xyz
- # Transformation matrix from XYZ (D50) to linear RGB (sRGB color space)
- M_XYZ_to_RGB_D50 = np.array([
- [ 3.1338561, -1.6168667, -0.4906146],
- [-0.9787684, 1.9161415, 0.0334540],
- [ 0.0719453, -0.2289914, 1.4052427]
- ])
- # Reshape xyz_d50 to (n, 3) for matrix multiplication
- xyz_d50_flat = xyz_d50.reshape(-1, 3)
- # Apply the transformation to get linear RGB
- rgb_linear_flat = np.dot(xyz_d50_flat, M_XYZ_to_RGB_D50.T)
- # Reshape back to original shape
- rgb_linear = rgb_linear_flat.reshape(xyz_d50.shape)
- # Gamma correction function
- def gamma_correction(channel):
- return np.where(channel <= 0.0031308,
- 12.92 * channel,
- 1.055 * np.power(channel, 1/2.4) - 0.055)
- # Apply gamma correction
- rgb_srgb = gamma_correction(rgb_linear)
- # Clip values to the range [0, 1]
- rgb_srgb = np.clip(rgb_srgb, 0, 1)
- return rgb_srgb
- # Example usage:
- # Assuming `xyz_data` is your input ndarray of shape (600, 800, 3)
- # xyz_data = np.random.random((600, 800, 3)) # Replace with actual data
- # rgb_data = xyz2rgb(xyz_data, white_point='D65')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement