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

OpenCV Python灰度视频转RGB视频报错求助:VideoWriter参数错误

灰度视频转彩色视频的OpenCV代码错误排查

问题描述

需要将灰度格式的视频转换为彩色格式,参考了Stack Overflow上的RGB转灰度问题及OpenCV官方cv::VideoWriter文档后,编写了如下Python代码:

import cv2
import matplotlib.pyplot as plt
source =cv2.VideoCapture("test_video.mp4")
frame_width = int(source.get(3))
frame_height = int(source.get(4))
size = (frame_width, frame_height,3)
result = cv2.VideoWriter('color_version.avi',
                         cv2.VideoWriter_fourcc(*'MJPG'),
                         10, size, True)
# running the loop
while True:
    # extracting the frames
    ret, img = source.read()
    # converting to color format
    colored = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    # write to gray-scale
    result.write(colored)
    # displaying the video
    cv2.imshow("Live", colored)
    # exiting the loop
    key = cv2.waitKey(1)
    if key == ord("q"):
        break
# closing the window
cv2.destroyAllWindows()
source.release()

运行后出现如下错误:

cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function 'VideoWriter'
> Overload resolution failed:
>  - Can't parse 'frameSize'. Expected sequence length 2, got 3
>  - Argument 'fps' can not be treated as a double
>  - Can't parse 'frameSize'. Expected sequence length 2, got 3
>  - VideoWriter() missing required argument 'params' (pos 6)

已设置isColor=true,但仍报错,询问代码问题所在。


错误原因及修正方案

1. VideoWriter的frameSize参数格式错误

OpenCV Python版的VideoWriter中,frameSize仅需传入二维元组(width, height),不需要包含通道数(第三个维度)。你设置的size = (frame_width, frame_height,3)是三维结构,直接触发了错误提示里的"Expected sequence length 2, got 3"。isColor=True仅用于告知框架写入的是彩色帧,通道数由实际写入的帧自动适配,无需在frameSize中声明。

2. 缺少帧读取成功的判断

循环中未判断ret是否为True,当视频读取到末尾时,img会变为None,此时调用cv2.cvtColor会引发新的报错。

3. 其他优化点

  • 移除未使用的matplotlib.pyplot导入,减少冗余;
  • 将fps参数显式写成10.0(浮点数),避免部分OpenCV版本的类型匹配问题;
  • 调整资源释放顺序,先释放VideoWriter和VideoCapture,再销毁窗口,更符合规范。

修正后的代码

import cv2

source = cv2.VideoCapture("test_video.mp4")
frame_width = int(source.get(3))
frame_height = int(source.get(4))
# 修正frameSize为二维元组
size = (frame_width, frame_height)
result = cv2.VideoWriter('color_version.avi',
                         cv2.VideoWriter_fourcc(*'MJPG'),
                         10.0,  # 显式使用浮点数fps
                         size, 
                         True)

while True:
    ret, img = source.read()
    # 判断帧读取是否成功,失败则退出循环
    if not ret:
        break
    # 将灰度帧转换为RGB彩色帧
    colored = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    result.write(colored)
    cv2.imshow("Live", colored)
    # 按下q键退出
    if cv2.waitKey(1) == ord("q"):
        break

# 按顺序释放资源
result.release()
source.release()
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:05:26