deepfakes/faceswap · error · ValueError

Error while reading image. This can be caused by special…

Error message

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)}

What it means

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.

Solutions

  1. Read the logged 'Original Error' to classify (IO vs decode vs permission) and fix that root cause
  2. For robust batch processing use raise_error=False and skip/log None returns so one bad frame doesn't kill a long job
  3. Pre-flight check readability: os.access(path, os.R_OK) and non-zero size before adding to the batch

Example fix

# before
imgs = [read_image(f, raise_error=True) for f in files]  # one OSError kills the batch

# after
imgs, skipped = [], []
for f in files:
    if not (os.path.isfile(f) and os.access(f, os.R_OK) and os.path.getsize(f) > 0):
        skipped.append(f); continue
    im = read_image(f, raise_error=False)
    (imgs if im is not None else skipped).append(im if im is not None else f)
# review skipped, rerun
Defensive patterns

Strategy: fallback

Validate before calling

import os

def preflight_image(path):
    return (os.path.isfile(path)
            and os.access(path, os.R_OK)
            and os.path.getsize(path) > 0)

batch = [f for f in files if preflight_image(f)]

Type guard

def safe_to_read(path: str) -> bool:
    """True when path exists, is readable and non-empty."""
    import os
    try:
        return os.path.isfile(path) and os.access(path, os.R_OK) and os.path.getsize(path) > 0
    except OSError:
        return False

Try / catch

imgs = []
for f in files:
    img = read_image(f, raise_error=False)
    if img is None:
        logger.warning("skipping unreadable frame: %s", f)
        continue
    imgs.append(img)

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Related errors


AI-assisted analysis of deepfakes/faceswap@f530cb7508 (2026-08-15). Data as JSON: /api/errors/de936449ac231414. Report an issue: GitHub.

Appendix: source

Thrown at lib/image.py:144

            assert isinstance(metadata, PNGHeader)
            retval = (image, metadata)
        else:
            retval = image
    except TypeError as err:
        success = False
        msg = f"Error while reading image (TypeError): '{filename}'"
        msg += f". Original error message: {str(err)}"
        logger.error(msg)
        if raise_error:
            raise TypeError(msg) from err
    except ValueError as err:
        success = False
        msg = ("Error while reading image. This can be caused by special characters in the "
               f"filename or a corrupt image file: '{filename}'")
        msg += f". Original error message: {str(err)}"
        logger.error(msg)
        if raise_error:
            raise ValueError(msg) from err
    except Exception as err:  # pylint:disable=broad-except
        success = False
        msg = f"Failed to load image '{filename}'. Original Error: {str(err)}"
        logger.error(msg)
        if raise_error:
            raise Exception(msg) from err  # pylint:disable=broad-exception-raised
    logger.trace("Loaded image: '%s'. Success: %s", filename, success)  # type:ignore[attr-defined]
    return retval


@T.overload
def read_image_batch(filenames: list[str], with_metadata: T.Literal[False] = False
                     ) -> np.ndarray: ...


@T.overload
def read_image_batch(filenames: list[str], with_metadata: T.Literal[True]
                     ) -> tuple[np.ndarray, list[PNGHeader]]: ...

View on GitHub (pinned to f530cb7508)