{"record":{"id":"da71baa45571095c","repo":"roboflow/supervision","slug":"failed-to-save-image-to-path-image-path","errorCode":null,"errorMessage":"Failed to save image to path: {image_path}","messagePattern":"Failed to save image to path: (.+?)","errorType":"exception","errorClass":"OSError","httpStatus":null,"severity":"error","filePath":"src/supervision/utils/image.py","lineNumber":734,"sourceCode":"        \"\"\"\n        Save image to target directory with optional custom filename.\n\n        Args:\n            image: Image to save with shape `(height, width, 3)`\n                in BGR format.\n            image_name: Custom filename for saved image. If\n                `None`, generates name using `image_name_pattern`. Defaults to\n                `None`.\n\n        Raises:\n            OSError: If `cv2.imwrite` cannot write the image to disk.\n        \"\"\"\n        if image_name is None:\n            image_name = self.image_name_pattern.format(self.image_count)\n\n        image_path = os.path.join(self.target_dir_path, image_name)\n        if not cv2.imwrite(image_path, image):\n            raise OSError(f\"Failed to save image to path: {image_path}\")\n        self.image_count += 1\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_value: BaseException | None,\n        exc_traceback: TracebackType | None,\n    ) -> None:\n        pass\n\n\n@deprecated(  # type: ignore[untyped-decorator]\n    target=TargetMode.NOTIFY,\n    deprecated_in=\"0.27.0\",\n    remove_in=\"0.31.0\",\n)\ndef create_tiles(\n    images: list[ImageType],","sourceCodeStart":716,"sourceCodeEnd":752,"githubUrl":"https://github.com/roboflow/supervision/blob/7f254d9784d4c37e0f03cd89ddee164c8db099c0/src/supervision/utils/image.py#L716-L752","documentation":"Raised by `ImageSink.save_image` when `cv2.imwrite` returns False, meaning OpenCV could not encode/write the image to the constructed path. `cv2.imwrite` signals failure by return value (it does not raise), so supervision converts it to an OSError with the target path. Typical root causes: unwritable directory, missing directory, unsupported/missing file extension, or an image dtype/channels OpenCV cannot encode.","triggerScenarios":"`ImageSink(target_dir_path='out/')` where `out/` does not exist (though the context manager creates it — occurs when saving outside `with`); `image_name_pattern='frame_{:05d}'` producing files with no extension; writing float32 arrays instead of uint8.","commonSituations":"Running in containers/CI where the mount is read-only; image name patterns that omit '.jpg'; exotic image shapes (odd dims for JPEG, 4-channel PNG mismatch); disk full.","solutions":["Ensure the target directory exists and is writable: `os.makedirs(path, exist_ok=True)`.","Include a valid extension in `image_name_pattern`, e.g. `'image_{:05d}.png'`.","Convert dtype/channels: `np.ascontiguousarray(image.astype(np.uint8))`, BGR 1- or 3-channel for JPEG.","Check disk space and container volume permissions."],"exampleFix":"# before\nwith sv.ImageSink(target_dir_path='out', image_name_pattern='frame_{:05d}') as sink:\n    sink.save_image(frame)  # no extension -> cv2.imwrite fails\n# after\nwith sv.ImageSink(target_dir_path='out', image_name_pattern='frame_{:05d}.png') as sink:\n    sink.save_image(frame)","handlingStrategy":"try-catch","validationCode":"os.makedirs(sink.target_dir_path, exist_ok=True)\nassert os.access(sink.target_dir_path, os.W_OK), 'target dir not writable'\n# ensure uint8 BGR contiguous image\nimage = np.ascontiguousarray(image.astype(np.uint8))","typeGuard":null,"tryCatchPattern":"try:\n    sink.save_image(frame)\nexcept OSError as e:\n    log.error('failed to write frame: %s', e)\n    raise  # or skip frame and continue the video loop","preventionTips":["Always include a valid extension in image_name_pattern.","Create and permission-check the target directory before the loop.","Use ImageSink only inside its `with` block so the directory is guaranteed to exist."],"tags":["image","save","opencv","filesystem","io"],"backgroundTag":null,"analyzedSha":"7f254d9784d4c37e0f03cd89ddee164c8db099c0","analyzedAt":"2026-08-15T05:13:01.950Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}