roboflow/supervision · error · TypeError

VideoWriter_fourcc requires exactly four characters

Error message

VideoWriter_fourcc requires exactly four characters

What it means

cv2.VideoWriter_fourcc is called as four single-character arguments, e.g. VideoWriter_fourcc(*'mp4v'). The fallback encodes the fourcc integer by shifting each character's ordinal, so it raises TypeError when it receives anything other than exactly four one-character strings — passing the packed string 'mp4v' as one argument fails.

Source

Thrown at src/supervision/_cv2/_video.py:41

    _CAP_PROP_POS_FRAMES,
)

logger = logging.getLogger(__name__)

_CODECS = {
    "mp4v": ("mpeg4", "yuv420p"),
    "xvid": ("mpeg4", "yuv420p"),
    "avc1": ("libx264", "yuv420p"),
    "h264": ("libx264", "yuv420p"),
    "mjpg": ("mjpeg", "yuvj420p"),
    "vp09": ("libvpx-vp9", "yuv420p"),
}


def _video_writer_fourcc(*chars: str) -> int:
    """Encode four single-character strings using OpenCV's integer layout."""
    if len(chars) != 4 or any(len(char) != 1 for char in chars):
        raise TypeError("VideoWriter_fourcc requires exactly four characters")
    return sum(ord(char) << (8 * index) for index, char in enumerate(chars))


def _decode_fourcc(fourcc: int) -> str:
    """Decode a fourcc integer into its four-character representation."""
    return "".join(chr((fourcc >> (8 * index)) & 0xFF) for index in range(4))


def _codec_details(fourcc: int) -> tuple[str, str]:
    """Return the PyAV codec and pixel format for a supported fourcc."""
    code = _decode_fourcc(fourcc).lower()
    try:
        return _CODECS[code]
    except KeyError as exc:
        raise ValueError(f"Unsupported video codec: {code!r}") from exc


class _VideoCapture:

View on GitHub (pinned to 7f254d9784)

Solutions

  1. Spread the string: fourcc = cv2.VideoWriter_fourcc(*'mp4v').
  2. Or pass four chars explicitly: cv2.VideoWriter_fourcc('m', 'p', '4', 'v').
  3. If the codec comes as a variable, assert len(codec) == 4 before unpacking.

Example fix

# before
fourcc = cv2.VideoWriter_fourcc('mp4v')

# after
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
Defensive patterns

Strategy: validation

Validate before calling

codec = 'mp4v'
assert len(codec) == 4 and codec.isascii()
fourcc = cv2.VideoWriter_fourcc(*codec)

Prevention

When it happens

Trigger: Calling cv2.VideoWriter_fourcc('mp4v') (one 4-char string) instead of cv2.VideoWriter_fourcc(*'mp4v') or ('m','p','4','v'); also passing fewer/more than four arguments.

Common situations: The classic OpenCV idiom cv2.VideoWriter_fourcc(*'mp4v') works, but hand-written variations like VideoWriter_fourcc('mp4v') or unpacking a list of the wrong length are common copy-paste bugs.

Related errors


AI-assisted analysis of roboflow/supervision@7f254d9784 (2026-08-15). Data as JSON: /api/errors/2fe6e313590aca6b. Report an issue: GitHub.