使用OpenCV实现直方图均衡化时imwrite函数报错:数据类型不支持
直方图均衡化imwrite报错解决
问题现象
运行直方图均衡化代码时,调用cv.imwrite保存图像触发错误:
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'imwrite'
Overload resolution failed:
- img data type = 17 is not supported
- Expected Ptrcv::UMat for argument 'img'
错误原因
np.hstack拼接两张灰度图后,生成的数组数据类型变为int64(对应OpenCV类型码17),而cv.imwrite不支持该数据类型,仅兼容uint8这类标准图像数据类型。
解决方法
- 先确认图像是否成功读取(避免路径错误导致
img为None) - 将拼接后的数组转换为
uint8类型再保存
修正后的代码
import numpy as np import cv2 as cv path = r'C:\Users\Lilly\Downloads\lena_color.jpg' img = cv.imread(path, 0) # 检查图像读取状态 if img is None: raise ValueError("图像读取失败,请检查路径是否正确") equ = cv.equalizeHist(img) res = np.hstack((img, equ)) # 转换为imwrite支持的uint8类型 cv.imwrite('res.png', res.astype(np.uint8))
也可以直接在拼接时指定类型:
res = np.hstack((img, equ)).astype(np.uint8) cv.imwrite('res.png', res)
内容的提问来源于stack exchange,提问作者than
相关产品推荐
相关产品推荐

