Matplotlib可显示白平衡图像但cv2.imwrite保存为黑图的解决方法
问题:白补丁白平衡校正后图像用
cv2.imwrite保存为全黑图像怎么办? 用户采用参考白法(白补丁白平衡)对RGB格式整数数组的原始图像做色彩校正,得到取值范围在0-1之间的浮点型数组。用Matplotlib能正常显示校正后的图像,但通过cv2.imwrite保存为JPG或PNG格式时,得到的是全黑图像,需解决正确保存的方法。
用户提供的校正代码如下:
def whitepatch_balancing(image, from_row, from_column, row_width, column_width): fig, ax = plt.subplots(1,2, figsize=(10,5)) ax[0].imshow(image) ax[0].add_patch(Circle((from_column, from_row), linewidth=3, edgecolor='r', facecolor='none')); ax[0].set_title('Original image') image_patch = image[from_row:from_row+row_width, from_column:from_column+column_width] image_max = (image*1.0 / image_patch.max(axis=(0, 1))).clip(0, 1) ax[1].imshow(image_max); ax[1].set_title('Whitebalanced Image with MAX value of white') plt.show() return image_max if __name__ == '__main__': image = imread('img.jpg') balanced_img = whitepatch_balancing(image, 60, 1230, 20, 20)
解决方案
原因分析
cv2.imwrite对输入图像格式有严格要求:
- 保存8位图像时,需要像素值为0-255的整数
- 保存16位图像时,需要像素值为0-65535的整数
而你的校正结果是0-1之间的浮点型数组,cv2.imwrite会直接将这些小数截断为0,最终保存出全黑图像。
解决步骤
只需将浮点型校正图像转换为符合要求的整数格式即可,具体操作如下:
映射浮点值到8位整数范围
对校正后的balanced_img执行数值转换:import numpy as np # 先确保数值在0-1范围内,再乘以255转换为uint8类型 save_img = (np.clip(balanced_img, 0, 1) * 255).astype('uint8')调整通道顺序(可选)
Matplotlib的imread读取的图像通道顺序是RGB,但OpenCV默认使用BGR通道顺序,直接保存会出现色彩偏差,需转换通道:import cv2 save_img_bgr = cv2.cvtColor(save_img, cv2.COLOR_RGB2BGR)调用
cv2.imwrite保存
最后执行保存操作:# 保存为JPG cv2.imwrite('balanced_image.jpg', save_img_bgr) # 或保存为PNG cv2.imwrite('balanced_image.png', save_img_bgr)
完整修改后的主函数示例
if __name__ == '__main__': import cv2 import numpy as np from matplotlib.image import imread from matplotlib import pyplot as plt from matplotlib.patches import Circle image = imread('img.jpg') balanced_img = whitepatch_balancing(image, 60, 1230, 20, 20) # 转换格式并保存 save_img = (np.clip(balanced_img, 0, 1) * 255).astype('uint8') save_img_bgr = cv2.cvtColor(save_img, cv2.COLOR_RGB2BGR) cv2.imwrite('balanced_img.jpg', save_img_bgr)
内容的提问来源于stack exchange,提问作者Yustas
相关产品推荐
相关产品推荐

