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

cv2.addWeighted报错:输入数组类型不同需指定输出类型

车道检测代码中cv2.addWeighted报错排查

问题重现

执行cv2.addWeighted(image, 1, lane_image, 1, 0)时触发以下错误:

cv2.error: OpenCV(4.6.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/core/src/arithm.cpp:674: error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function 'arithm_op'

相关代码片段:

# Get image ready for feeding into model
#small_img = imresize(image, (80, 160, 3))
small_img  = resize(image, (80,160), order=3)

small_img = np.array(small_img)
small_img = small_img[None,:,:,:]

# Make prediction with neural network (un-normalize value by multiplying by 255)
prediction = model.predict(small_img)[0] * 255

# Add lane prediction to list for averaging
lanes.recent_fit.append(prediction)
# Only using last five for average
if len(lanes.recent_fit) > 5:
    lanes.recent_fit = lanes.recent_fit[1:]

# Calculate average detection
lanes.avg_fit = np.mean(np.array([i for i in lanes.recent_fit]), axis = 0)

# Generate fake R & B color dimensions, stack with G
blanks = np.zeros_like(lanes.avg_fit).astype(np.uint8)
lane_drawn = np.dstack((blanks, lanes.avg_fit, blanks))

# Re-size to match the original image
#lane_image = imresize(lane_drawn, (720, 1280, 3))
lane_image = resize(lane_drawn, (720,1280), order=3)

# Merge the lane drawing onto the original image
result = cv2.addWeighted(image, 1, lane_image, 1, 0)

return result

错误原因

  • 原始图像image通常为uint8类型(像素值范围0-255的整数),而经过模型预测、均值计算后的lanes.avg_fit是浮点型,后续通过dstack和resize生成的lane_image也保留了浮点类型。
  • cv2.addWeighted要求输入数组的数据类型一致;当输入类型不同时,必须显式指定输出数组的类型,否则会触发该参数错误。

解决方案

方案一:统一输入数组类型

将lane_image转换为与image一致的uint8类型,在resize后添加类型转换代码:

# Re-size to match the original image
lane_image = resize(lane_drawn, (720,1280), order=3)
# 转换为uint8类型,确保像素值在0-255范围内
lane_image = lane_image.astype(np.uint8)

注:当前代码中prediction已通过*255完成反归一化,均值后的lanes.avg_fit值范围在0-255之间,直接转换不会出现数值溢出问题。

方案二:显式指定输出数组类型

调用cv2.addWeighted时,通过dtype参数强制指定输出类型为uint8:

# Merge the lane drawing onto the original image
result = cv2.addWeighted(image, 1, lane_image, 1, 0, dtype=cv2.CV_8U)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:09:22