{"record":{"id":"9f9693437b708769","repo":"deepinsight/insightface","slug":"video-writer-could-not-be-opened","errorCode":null,"errorMessage":"Video writer could not be opened.","messagePattern":"Video writer could not be opened\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python-package/insightface/gui/pages/face_swap_page.py","lineNumber":251,"sourceCode":"        except Exception as exc:\n            raise ValueError(f\"OpenCV is required for video face swap: {exc}\") from exc\n\n        cap = cv2.VideoCapture(target_path)\n        if not cap.isOpened():\n            raise ValueError(\"Video could not be opened.\")\n        fps = cap.get(cv2.CAP_PROP_FPS) or 25.0\n        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)\n        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)\n        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)\n        if width <= 0 or height <= 0:\n            cap.release()\n            raise ValueError(\"Video dimensions could not be read.\")\n        output_path = Path(self.context.config.export_dir) / f\"face_swap_video_{timestamp_for_filename()}.mp4\"\n        output_path.parent.mkdir(parents=True, exist_ok=True)\n        writer = cv2.VideoWriter(str(output_path), cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height))\n        if not writer.isOpened():\n            cap.release()\n            raise ValueError(\"Video writer could not be opened.\")\n\n        preview = None\n        swapped = 0\n        processed = 0\n        try:\n            while True:\n                if is_cancelled and is_cancelled():\n                    break\n                ok, frame = cap.read()\n                if not ok:\n                    break\n                output_frame = frame\n                target_face = self.context.engine.detect_best_face(frame, source_path=target_path)\n                if target_face is not None and target_face.kps is not None:\n                    target_native = SimpleNamespace(kps=np.asarray(target_face.kps, dtype=np.float32))\n                    output_frame = swapper.swap(frame, target_native, source_native)\n                    swapped += 1\n                    if preview is None:","sourceCodeStart":233,"sourceCodeEnd":269,"githubUrl":"https://github.com/deepinsight/insightface/blob/7fadd420c2351d0ffa8cac403421c1a3ed733365/python-package/insightface/gui/pages/face_swap_page.py#L233-L269","documentation":"cv2.VideoWriter failed to open the output MP4 (writer.isOpened() False) — the mp4v codec could not be initialized for the given path/fps/size combination, so the swapped video cannot be written.","triggerScenarios":"The export directory is unwritable, disk is full, or the OpenCV build lacks the mp4v (MPEG-4 part 2) encoder; also occurs with unusual fps values like 0 or inf, or zero dimensions passed through.","commonSituations":"Headless Docker images with opencv-python-headless lacking encoder support, read-only export_dir config, extremely high fps reported by broken streams, or paths containing characters the backend rejects.","solutions":["Check export_dir exists, is writable, and the disk has free space","Try 'avc1' or 'XVID' (.avi) fourcc instead of 'mp4v'","Sanitize fps: clamp to a sane range (e.g. 1–120) before constructing the writer","If the encoder is missing, install full opencv-python or write frames with imageio/ffmpeg instead"],"exampleFix":"# before\nwriter = cv2.VideoWriter(str(out), cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (w, h))\n# after\nfps = min(max(fps, 1.0), 120.0)\nfourcc = cv2.VideoWriter_fourcc(*\"avc1\")\nwriter = cv2.VideoWriter(str(out), fourcc, fps, (w, h))\nif not writer.isOpened():\n    writer = cv2.VideoWriter(str(out.with_suffix(\".avi\")), cv2.VideoWriter_fourcc(*\"XVID\"), fps, (w, h))","handlingStrategy":"fallback","validationCode":"fps = float(fps or 25.0); fps = min(max(fps, 1.0), 120.0\nif width > 0 and height > 0 and os.access(out_dir, os.W_OK):\n    writer = cv2.VideoWriter(...)","typeGuard":null,"tryCatchPattern":"try:\n    return self._swap_video(...)\nexcept ValueError as e:\n    if 'writer' in str(e): write_avi_xvid_fallback()","preventionTips":["Pre-create and permission-check export_dir","Try avc1 then XVID/avi fallback","Clamp fps and validate dimensions before constructing the writer"],"tags":["insightface","opencv","video-writer","codec"],"backgroundTag":"opencv-videowriter-open-failed","analyzedSha":"7fadd420c2351d0ffa8cac403421c1a3ed733365","analyzedAt":"2026-08-28T15:44:01.850Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}