OpenCV用cv2.rectangle绘图后保存仅显矩形,如何存与imshow一致的图像
问题解决方法
原因分析
你遇到的问题核心是图像数据格式/保存接口的匹配问题:matplotlib的imshow同时支持01范围的浮点型图像和0255范围的uint8型图像,但绝大多数自定义save_img函数、OpenCV原生保存接口仅识别0255范围的uint8格式。如果你的底图`x1`是01的浮点型,只有绘制矩形时写入的255数值会被保存接口识别,其余低数值会被截断为0,最终出现仅保留矩形的黑图。
最优解决方案(和imshow效果100%一致)
直接用matplotlib的保存接口存储当前展示的画布即可,无需依赖第三方保存函数,代码示例:
import matplotlib.pyplot as plt import cv2 import numpy as np start_point = (centerXList[i] +16,centerYList[i]-14) end_point = (centerXList[i]+50,centerYList[i]+24) color=(255,0,0) x1=cv2.rectangle(x1,start_point,end_point,color) # 先完成格式校验,避免显示/保存异常 if x1.max() <= 1.0: x1 = (x1 * 255).astype(np.uint8) # 绘制并保存 plt.figure() plt.imshow(x1) plt.axis('off') # 关闭坐标轴,和纯图展示效果一致 # 保存时去掉多余白边,可自行调整dpi控制清晰度 plt.savefig("./Predicted Images/abc.jpeg", bbox_inches='tight', pad_inches=0, dpi=300) plt.show()
备选方案(用OpenCV原生接口保存)
如果需要用OpenCV保存,注意先做通道转换(OpenCV默认BGR顺序,matplotlib默认RGB顺序,直接保存会有色差):
# 格式校验 if x1.max() <= 1.0: x1 = (x1 * 255).astype(np.uint8) # 转BGR通道 x1_bgr = cv2.cvtColor(x1, cv2.COLOR_RGB2BGR) cv2.imwrite("./Predicted Images/abc.jpeg", x1_bgr)
内容的提问来源于stack exchange,提问作者Priyam Thakkar
相关产品推荐
相关产品推荐

