{"record":{"id":"c75278472fde8ad9","repo":"roboflow/supervision","slug":"could-not-open-video-writer-for-self-target-path","errorCode":null,"errorMessage":"Could not open video writer for {self.target_path}","messagePattern":"Could not open video writer for (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/supervision/utils/video.py","lineNumber":142,"sourceCode":"        fourcc_fn = cast(\n            Callable[[str, str, str, str], int], getattr(cv2, \"VideoWriter_fourcc\")\n        )\n        try:\n            self.__fourcc = int(fourcc_fn(*self.__codec))\n        except TypeError as e:\n            logger.warning(\"%s. Defaulting to mp4v...\", str(e))\n            self.__fourcc = int(fourcc_fn(*\"mp4v\"))\n        self.__writer = cv2.VideoWriter(\n            self.target_path,\n            self.__fourcc,\n            self.video_info.fps,\n            self.video_info.resolution_wh,\n        )\n        # OpenCV can construct a writer object that is not usable for the target path.\n        if not self.__writer.isOpened():\n            self.__writer.release()\n            self.__writer = None\n            raise RuntimeError(f\"Could not open video writer for {self.target_path}\")\n        return self\n\n    def write_frame(self, frame: npt.NDArray[np.uint8]) -> None:\n        \"\"\"\n        Writes a single video frame to the target video file.\n\n        Args:\n            frame: The video frame to be written to the file. The frame\n                must be in BGR color format.\n        \"\"\"\n        # Preserve the context-manager invariant instead of silently dropping frames.\n        if self.__writer is None:\n            raise RuntimeError(\"write_frame requires an open VideoSink context.\")\n        self.__writer.write(frame)\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/roboflow/supervision/blob/7f254d9784d4c37e0f03cd89ddee164c8db099c0/src/supervision/utils/video.py#L124-L160","documentation":"Raised by VideoSink.__enter__ (via its writer setup) in supervision.utils.video when cv2.VideoWriter constructs but fails to actually open the target path (isOpened() is False). OpenCV regularly returns a writer object for impossible targets — bad directory, unwritable location, or an unsupported FOURCC/container combination — so supervision checks isOpened() and raises RuntimeError after releasing the dead writer.","triggerScenarios":"with sv.VideoSink('out/x.mp4', video_info) as sink: when out/ does not exist; using codec='x264' without the codec available locally; writing .avi with an mp4-oriented FOURCC; target on read-only storage.","commonSituations":"Output directories never created (mkdir -p forgotten); codec string from a tutorial that the local OpenCV build cannot encode; permission-restricted mount or container filesystem; extension/FOURCC mismatch like video_codec='mp4v' with a .avi name.","solutions":["Create the parent directory first: os.makedirs(os.path.dirname(target_path) or '.', exist_ok=True).","Fall back to a widely available codec: VideoSink(..., video_codec='mp4v') with a .mp4 name.","Check write permission on the target directory (os.access(dir, os.W_OK)).","Verify with a minimal cv2.VideoWriter test if a custom FOURCC is required."],"exampleFix":"// before\nwith sv.VideoSink('output/out.mp4', info) as sink:  # output/ missing\n\n// after\nos.makedirs('output', exist_ok=True)\nwith sv.VideoSink('output/out.mp4', info) as sink:\n    ...","handlingStrategy":"validation","validationCode":"target_dir = os.path.dirname(os.path.abspath(target_path))\nos.makedirs(target_dir, exist_ok=True)\nif not os.access(target_dir, os.W_OK):\n    raise PermissionError(target_dir)\nwith sv.VideoSink(target_path, info, video_codec='mp4v') as sink:\n    ...","typeGuard":null,"tryCatchPattern":"try:\n    sink_ctx = sv.VideoSink(target_path, info)\n    sink_ctx.__enter__()\nexcept RuntimeError as e:\n    if 'Could not open video writer' in str(e):\n        sink_ctx = sv.VideoSink(fallback_path, info, video_codec='mp4v')\n        sink_ctx.__enter__()\n    else:\n        raise","preventionTips":["Create output directories before opening sinks.","Prefer the portable 'mp4v' codec unless a specific codec is verified available.","Match file extension to codec/container to avoid OpenCV writer rejection."],"tags":["video","opencv","file-io","codec"],"backgroundTag":null,"analyzedSha":"7f254d9784d4c37e0f03cd89ddee164c8db099c0","analyzedAt":"2026-08-15T05:13:01.950Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}