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

使用np.dstack堆叠图像后,cv2.imwrite保存报错求助

解决cv2.imwrite保存堆叠图像时的Bad argument错误

错误原因分析

  1. 变量名拼写错误:代码里定义了final_img_arr,但后续调用了未定义的FinalImage,会先触发NameError,修正后才会遇到imwrite的参数问题
  2. 参数类型不匹配:cv2.imwrite要求传入的图像是numpy数组或OpenCV的UMat对象,但你最后传的是PIL库的Image实例(FinalImage2),完全不符合要求
  3. 通道数兼容性:用np.dstack堆叠两个单通道数组得到的是2通道图像,部分图像格式(如JPG)不支持保存2通道数据,TIFF虽支持,但也要确保处理流程正确

修正方案

方案一:全程用numpy数组+OpenCV保存

修正变量名,直接处理numpy数组后传给cv2.imwrite:

import cv2
import numpy as np
from PIL import Image, ImageDraw

# 读取图像
img = cv2.imread('Input-Set/Original1.tif')

# 转灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 平滑处理
blur = cv2.blur(gray,(3,3))

# 阈值处理
ret, th1 = cv2.threshold(blur,145,255,cv2.THRESH_BINARY)
inverted = np.invert(th1)

# 背景阈值处理
ret, th2 = cv2.threshold(blur,1,255,cv2.THRESH_BINARY)

# 掩码处理
masked = cv2.bitwise_and(inverted, inverted, mask=th2)

height = 998
width = 1024
# 创建圆形掩码
lum_img = Image.new('L', [height,width] , 0)
draw = ImageDraw.Draw(lum_img)
draw.pieslice([(16,37), (960,985)], 0, 360, fill=255, outline="white")
lum_img_arr = np.array(lum_img)
img_arr = np.array(th1)

# 堆叠成2通道数组
final_img_arr = np.dstack((lum_img_arr, img_arr))
# 反转图像
inverted2 = np.invert(final_img_arr)

# 直接用cv2保存numpy数组
cv2.imwrite('Output-Set/FinalImage2.tif', inverted2)

方案二:用PIL保存图像

如果习惯用PIL处理,就不要混用OpenCV的保存方法,直接用PIL的save:

# 前面代码和方案一一致,到inverted2之后:
FinalImage2 = Image.fromarray(inverted2)
FinalImage2.save('Output-Set/FinalImage2.tif')

额外提示

  • Python对变量名大小写敏感,一定要注意final_img_arr和FinalImage这类大小写差异,避免未定义错误
  • 如果需要保存为通用格式(如JPG/PNG),可以把2通道数组转成3通道,比如重复通道:
    # 将2通道转成3通道
    final_img_3ch = np.repeat(final_img_arr[:, :, np.newaxis], 3, axis=2)
    

内容的提问来源于stack exchange,提问作者Abdullah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:55:54