deepinsight/insightface · error · ValueError

OpenCV is required for video face swap: {exc}

Error message

OpenCV is required for video face swap: {exc}

What it means

Thrown when the cv2 (OpenCV) import inside _swap_video fails; video face swap requires OpenCV for VideoCapture/VideoWriter, and the import exception is chained into the ValueError message.

Source

Thrown at python-package/insightface/gui/pages/face_swap_page.py:234

        target_face = self.context.engine.detect_best_face(target_image, source_path=target_path)
        if target_face is None or target_face.kps is None:
            raise ValueError("No usable face detected in target image.")
        target_native = SimpleNamespace(kps=np.asarray(target_face.kps, dtype=np.float32))
        image = swapper.swap(target_image, target_native, source_native)
        output_path = Path(self.context.config.export_dir) / f"face_swap_{timestamp_for_filename()}.png"
        save_image(output_path, image)
        return {
            "kind": "image",
            "image": image,
            "path": str(output_path),
            "message": f"Image face swap saved to {output_path}",
        }

    def _swap_video(self, swapper: FaceSwapEngine, source_native, target_path: str, progress=None, is_cancelled=None) -> dict:
        try:
            import cv2
        except Exception as exc:
            raise ValueError(f"OpenCV is required for video face swap: {exc}") from exc

        cap = cv2.VideoCapture(target_path)
        if not cap.isOpened():
            raise ValueError("Video could not be opened.")
        fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
        if width <= 0 or height <= 0:
            cap.release()
            raise ValueError("Video dimensions could not be read.")
        output_path = Path(self.context.config.export_dir) / f"face_swap_video_{timestamp_for_filename()}.mp4"
        output_path.parent.mkdir(parents=True, exist_ok=True)
        writer = cv2.VideoWriter(str(output_path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
        if not writer.isOpened():
            cap.release()
            raise ValueError("Video writer could not be opened.")

View on GitHub (pinned to 7fadd420c2)

Solutions

  1. Read the chained {exc} text: if libGL.so.1 missing, install system package libgl1 (and libglib2.0-0)
  2. pip install opencv-python (or use opencv-python-headless in servers/containers)
  3. Reinstall cleanly: pip uninstall opencv-python opencv-python-headless -y then install one variant
  4. Verify with python -c "import cv2" before retrying

Example fix

# before (container)
# pip install opencv-python -> import fails on libGL
# after
pip install opencv-python-headless
# or: apt-get install -y libgl1 libglib2.0-0
Defensive patterns

Strategy: validation

Validate before calling

try:
    import cv2  # noqa
except Exception:
    disable_video_tab_with_message('pip install opencv-python')

Try / catch

try:
    return self._swap_video(...)
except ValueError as e:
    if 'OpenCV is required' in str(e): run_pip('opencv-python-headless')

Prevention

When it happens

Trigger: Starting a video face swap in an environment where cv2 is not installed, or where importing cv2 raises (broken install, missing libGL/libgthread shared libraries on Linux).

Common situations: Headless Linux containers missing libgl1 causing 'cv2.error: libGL.so.1 cannot be opened', partial pip installs, opencv-python uninstalled as a dependency conflict resolution.

Related errors


AI-assisted analysis of deepinsight/insightface@7fadd420c2 (2026-08-28). Data as JSON: /api/errors/0d7a0b7406201072. Report an issue: GitHub.