Python中RGB与TSL色彩空间互转无法还原图像的问题排查
TSL-RGB色彩空间转换无法还原原始图像问题
我用Python实现了RGB到TSL(色调Tint、饱和度Saturation、明度Lightness)色彩空间的转换函数,同时编写了反向转换函数用于验证图像能否正确还原,以此确认实现逻辑的准确性。但目前反向转换无法还原出原始输入图像,不确定错误出在哪个环节。
TSL转RGB的实现参考了维基百科对应公式,RGB转TSL则参考了原始论文,且已采纳@statemachine的修改建议。
实现代码
import cv2 import numpy as np def rgb_tsl(image_path, gamma_factor): # OpenCV默认读取BGR顺序 object_data = cv2.imread(image_path) # 归一化到0-1范围 scaled_data = object_data / 255 # Gamma校正 corrected_image_gamma = np.power(scaled_data, gamma_factor) # 拆分通道(BGR顺序) base_blue_channel = corrected_image_gamma[:, :, 0] base_green_channel = corrected_image_gamma[:, :, 1] base_red_channel = corrected_image_gamma[:, :, 2] # 计算T、S、L分量 common_divisor = (base_red_channel + base_green_channel + base_blue_channel) small_r = base_red_channel / common_divisor small_g = base_green_channel / common_divisor r_hyphen = small_r - (1/3) g_hyphen = small_g - (1/3) luma = (0.299 * base_red_channel) + (0.587 * base_green_channel) + (0.114 * base_blue_channel) saturation = np.sqrt((9/5)*(np.power(r_hyphen, 2) + np.power(g_hyphen, 2))) # 计算色调Tint tint_arr = np.zeros_like(g_hyphen) for index, item in np.ndenumerate(g_hyphen): if item == 0: tint_arr[index] = 0 else: corresponding_r_hyphen = r_hyphen[index] if item < 0: arctan_value_less_zero = ((np.arctan(corresponding_r_hyphen / item)) / (2 * np.pi)) + (3/4) tint_arr[index] = arctan_value_less_zero else: arctan_value_greater_zero = ((np.arctan(corresponding_r_hyphen / item)) / (2 * np.pi)) + (1 / 4) tint_arr[index] = arctan_value_greater_zero merged_image = cv2.merge([tint_arr, saturation, luma]) merged_image = (255 * merged_image).astype(np.uint8) # 修复原函数返回值缺失问题,保证调用时能解构出原始图像 return object_data, merged_image def tsl_rgb(image): tint = image[:, :, 0] / 255.0 saturation = image[:, :, 1] / 255.0 luma = image[:, :, 2] / 255.0 x_val = np.power(np.tan((2 * np.pi) * (tint - (1/4))), 2) r_hyphen_tsl = np.sqrt((5 * np.power(saturation, 2)) / 9 * ((1/x_val) + 1)) g_hyphen_tsl = np.sqrt((5 * np.power(saturation, 2)) / 9 * (x_val + 1)) r_tsl = r_hyphen_tsl + (1/3) g_tsl = g_hyphen_tsl + (1/3) k = luma / ((0.185 * r_tsl) + (0.473 * g_tsl) + 0.114) final_r = k * r_tsl final_g = k * g_tsl final_b = k * (1-r_tsl-g_tsl) # 修复通道顺序问题,匹配OpenCV的BGR格式 final_rgb_image = cv2.merge([final_b, final_g, final_r]) clippedImg = np.clip(final_rgb_image, 0, 1) final_rgb_image = (255 * clippedImg).astype(np.uint8) return final_rgb_image # 测试路径 current_image_path = '/home/xyz/Data_Science/Skin Cancer/ISIC_0034202_dullrazor.jpg' # Gamma校正系数参考行业标准值 original_img, converted_image_tsl = rgb_tsl(current_image_path, 1.5) reverse_image = tsl_rgb(converted_image_tsl) cv2.imshow("Original RGB image", original_img) cv2.imshow("TSL image", converted_image_tsl) cv2.imshow("Re-constructed RGB image", reverse_image) cv2.waitKey(0) cv2.destroyAllWindows()
当前输出效果
- 原始RGB图像

- RGB转TSL后的图像

- TSL还原后的RGB图像

内容的提问来源于stack exchange,提问作者Dhruv Marwha
相关产品推荐
相关产品推荐

