You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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这类标准图像数据类型。

解决方法

  1. 先确认图像是否成功读取(避免路径错误导致img为None)
  2. 将拼接后的数组转换为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:05:39