{"record":{"id":"de936449ac231414","repo":"deepfakes/faceswap","slug":"error-while-reading-image-this-can-be-caused-by-s","errorCode":null,"errorMessage":"Error while reading image. This can be caused by special characters in the filename or a corrupt image file: '{filename}'. Original error message: {str(err)}","messagePattern":"Error while reading image\\. This can be caused by special characters in the filename or a corrupt image file: '(.+?)'\\. Original error message: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/image.py","lineNumber":144,"sourceCode":"            assert isinstance(metadata, PNGHeader)\n            retval = (image, metadata)\n        else:\n            retval = image\n    except TypeError as err:\n        success = False\n        msg = f\"Error while reading image (TypeError): '{filename}'\"\n        msg += f\". Original error message: {str(err)}\"\n        logger.error(msg)\n        if raise_error:\n            raise TypeError(msg) from err\n    except ValueError as err:\n        success = False\n        msg = (\"Error while reading image. This can be caused by special characters in the \"\n               f\"filename or a corrupt image file: '{filename}'\")\n        msg += f\". Original error message: {str(err)}\"\n        logger.error(msg)\n        if raise_error:\n            raise ValueError(msg) from err\n    except Exception as err:  # pylint:disable=broad-except\n        success = False\n        msg = f\"Failed to load image '{filename}'. Original Error: {str(err)}\"\n        logger.error(msg)\n        if raise_error:\n            raise Exception(msg) from err  # pylint:disable=broad-exception-raised\n    logger.trace(\"Loaded image: '%s'. Success: %s\", filename, success)  # type:ignore[attr-defined]\n    return retval\n\n\n@T.overload\ndef read_image_batch(filenames: list[str], with_metadata: T.Literal[False] = False\n                     ) -> np.ndarray: ...\n\n\n@T.overload\ndef read_image_batch(filenames: list[str], with_metadata: T.Literal[True]\n                     ) -> tuple[np.ndarray, list[PNGHeader]]: ...","sourceCodeStart":126,"sourceCodeEnd":162,"githubUrl":"https://github.com/deepfakes/faceswap/blob/f530cb7508ae670f6474f8a7d9c4df94705cf96b/lib/image.py#L126-L162","documentation":"Catch-all branch of read_image_wrap: any exception other than TypeError/ValueError during image loading (OSError/IOError from unreadable files, PermissionError, cv2 errors, decompression errors) is logged with the original error and re-raised as bare Exception only when raise_error=True; with raise_error=False the function returns None (retval stays unset/None) and logs success=False.","triggerScenarios":"read_image(filename, raise_error=True) where the file is missing mid-read, permissions deny access, the network mount drops, or an unexpected decoder error occurs (e.g. cv2.error for unsupported formats like some TIFF/EXR variants).","commonSituations":"Network filesystems dropping during batch reads; files deleted by another process mid-run; permission changes on extracted frames; exotic image formats unsupported by the bundled OpenCV.","solutions":["Read the logged 'Original Error' to classify (IO vs decode vs permission) and fix that root cause","For robust batch processing use raise_error=False and skip/log None returns so one bad frame doesn't kill a long job","Pre-flight check readability: os.access(path, os.R_OK) and non-zero size before adding to the batch"],"exampleFix":"# before\nimgs = [read_image(f, raise_error=True) for f in files]  # one OSError kills the batch\n\n# after\nimgs, skipped = [], []\nfor f in files:\n    if not (os.path.isfile(f) and os.access(f, os.R_OK) and os.path.getsize(f) > 0):\n        skipped.append(f); continue\n    im = read_image(f, raise_error=False)\n    (imgs if im is not None else skipped).append(im if im is not None else f)\n# review skipped, rerun","handlingStrategy":"fallback","validationCode":"import os\n\ndef preflight_image(path):\n    return (os.path.isfile(path)\n            and os.access(path, os.R_OK)\n            and os.path.getsize(path) > 0)\n\nbatch = [f for f in files if preflight_image(f)]","typeGuard":"def safe_to_read(path: str) -> bool:\n    \"\"\"True when path exists, is readable and non-empty.\"\"\"\n    import os\n    try:\n        return os.path.isfile(path) and os.access(path, os.R_OK) and os.path.getsize(path) > 0\n    except OSError:\n        return False","tryCatchPattern":"imgs = []\nfor f in files:\n    img = read_image(f, raise_error=False)\n    if img is None:\n        logger.warning(\"skipping unreadable frame: %s\", f)\n        continue\n    imgs.append(img)","preventionTips":["Use raise_error=False plus None-checks for resilience in batch jobs","Pre-check os.access/getsize on network or shared filesystems","Log and quarantine unreadable files instead of aborting long runs"],"tags":["faceswap","image-io","robustness","io","batch"],"backgroundTag":null,"analyzedSha":"f530cb7508ae670f6474f8a7d9c4df94705cf96b","analyzedAt":"2026-08-15T02:59:26.626Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}