Advertisement
ajith_97

Xyz2rgb

May 29th, 2024
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def xyz2rgb(xyz, white_point='D50'):
  4. # Normalize XYZ if not already normalized
  5. xyz = np.array(xyz, dtype=np.float32) # Ensure the array is in float
  6. xyz /= np.max(xyz)
  7.  
  8. if white_point == 'D65':
  9. # White point adaptation matrix from D65 to D50 using Bradford transformation
  10. M_D65_to_D50 = np.array([
  11. [ 0.9555766, -0.0230393, 0.0631636],
  12. [-0.0282895, 1.0099416, 0.0210077],
  13. [ 0.0122982, -0.0204830, 1.3299098]
  14. ])
  15. # Reshape xyz to (n, 3) for matrix multiplication
  16. xyz_flat = xyz.reshape(-1, 3)
  17. # Apply the white point adaptation
  18. xyz_d50_flat = np.dot(xyz_flat, M_D65_to_D50.T)
  19. # Reshape back to original shape
  20. xyz_d50 = xyz_d50_flat.reshape(xyz.shape)
  21. else:
  22. # No adaptation needed if already in D50
  23. xyz_d50 = xyz
  24.  
  25. # Transformation matrix from XYZ (D50) to linear RGB (sRGB color space)
  26. M_XYZ_to_RGB_D50 = np.array([
  27. [ 3.1338561, -1.6168667, -0.4906146],
  28. [-0.9787684, 1.9161415, 0.0334540],
  29. [ 0.0719453, -0.2289914, 1.4052427]
  30. ])
  31.  
  32. # Reshape xyz_d50 to (n, 3) for matrix multiplication
  33. xyz_d50_flat = xyz_d50.reshape(-1, 3)
  34.  
  35. # Apply the transformation to get linear RGB
  36. rgb_linear_flat = np.dot(xyz_d50_flat, M_XYZ_to_RGB_D50.T)
  37.  
  38. # Reshape back to original shape
  39. rgb_linear = rgb_linear_flat.reshape(xyz_d50.shape)
  40.  
  41. # Gamma correction function
  42. def gamma_correction(channel):
  43. return np.where(channel <= 0.0031308,
  44. 12.92 * channel,
  45. 1.055 * np.power(channel, 1/2.4) - 0.055)
  46.  
  47. # Apply gamma correction
  48. rgb_srgb = gamma_correction(rgb_linear)
  49.  
  50. # Clip values to the range [0, 1]
  51. rgb_srgb = np.clip(rgb_srgb, 0, 1)
  52.  
  53. return rgb_srgb
  54.  
  55. # Example usage:
  56. # Assuming `xyz_data` is your input ndarray of shape (600, 800, 3)
  57. # xyz_data = np.random.random((600, 800, 3)) # Replace with actual data
  58. # rgb_data = xyz2rgb(xyz_data, white_point='D65')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement