如何用OpenCV和Numpy复刻Fabric.js的图像色相旋转效果?
实现与Fabric.js一致的Python色相旋转效果
我正在进行图像滤波工作,需要使用Python调整图像色相。此前用Fabric.js执行色相旋转,效果满意但运行速度极慢,因此希望将该功能复刻到Python中。然而尝试用OpenCV和Numpy实现时,输出结果与Fabric.js存在明显差异,人眼可轻易识别,部分区域绝对误差(AE)超15%。
以下是我的Python简化代码:
def adjust_hue(image, hue_value): """ changes the Hue of the image using the hue_value parameter and returns the adjusted image. The hue_value must be in range (-1, 1). """ # Split the input image into the color channels (BGR) and alpha channel bgr_channels = image[:, :, :3] alpha_channel = image[:, :, 3] hue_value = (hue_value * 180) / 2 # Convert BGR image to HSV color space hsv_image = cv2.cvtColor(bgr_channels, cv2.COLOR_BGR2HSV) # Adjust the hue of the HSV image hsv_image[:, :, 0] = (hsv_image[:, :, 0] + hue_value) % 180 # Convert the adjusted HSV image back to BGR color space bgr_adjusted = cv2.cvtColor(hsv_image, cv2.COLOR_HSV2BGR) # Merge the adjusted BGR channels with the original alpha channel result_image = np.dstack((bgr_adjusted, alpha_channel)) return result_image # 调用方式 rotation = 0.33333333333333333333333333333333 # 对应-180到180范围里的60度 filtered_image = adjust_hue(image, rotation) cv2.imwrite('merged.png', filtered_image)
Fabric.js的色相参数范围为(-1,1),我沿用了该范围。尝试通过hue_value = (hue_value * 180)将其转换为(-180,180)时,输出不符合预期(如传入0.333...对应60度,效果却像传入120度),因此改为除以2的转换方式。输入图像为带透明通道的PNG格式,当前输出与Fabric.js预期输出存在差异,恳请指导如何实现与Fabric.js一致的精准色相旋转效果。
使用的依赖包:
- numpy==1.24.4
- opencv-python==4.8.0.74
内容的提问来源于stack exchange,提问作者Barun Bhattacharjee
相关产品推荐
相关产品推荐

