deepfakes/faceswap · error · TypeError

Error while reading image (TypeError): '{filename}'. Origina

Error message

Error while reading image (TypeError): '{filename}'. Original error message: {str(err)}

What it means

read_image_wrap ValueError branch: PIL/cv2 raise ValueError for data they can identify as image-like but cannot parse — Faceswap calls out the two dominant causes in the message: special characters in the filename or a corrupt image file.

Source

Thrown at lib/image.py:136

            # Just naively clip floating images to 0-1 for now
            image = (np.clip(image, 0.0, 1.0) * 255.).astype(np.float32)

        if image.dtype != np.uint8:
            image = np.clip(image, 0, 255).astype(np.uint8)

        if with_metadata:
            metadata = png_read_meta(raw_file)
            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

View on GitHub (pinned to f530cb7508)

Solutions

  1. Rename/sanitize the file and path to plain ASCII (no accents, spaces, emoji) and retry
  2. Verify the file opens in an image viewer or with PIL.Image.open(path).verify(); re-export or delete if corrupt
  3. If sanitizing thousands of paths, write a normalization pass that maps old->new names and update the alignments file keys accordingly

Example fix

# before
img = read_image("C:/data/héllo wörld/000001.png", raise_error=True)

# after
import shutil, os
os.rename(r"C:\data\héllo wörld", r"C:\data\hello_world")
img = read_image("C:/data/hello_world/000001.png", raise_error=True)
Defensive patterns

Strategy: validation

Validate before calling

import os, unicodedata, re

def safe_ascii_path(path):
    name = unicodedata.normalize("NFKD", os.path.basename(path))
    name = name.encode("ascii", "ignore").decode()
    name = re.sub(r"[^A-Za-z0-9_.-]", "_", name)
    return os.path.join(os.path.dirname(path), name or "unnamed")

# verify decodability before read_image
from PIL import Image
assert Image.open(path).verify() is None or True

Type guard

def is_ascii_image_path(path: str) -> bool:
    """True when path has no non-ASCII chars that break cv2.imread."""
    return path.isascii()

Try / catch

try:
    img = read_image(path, raise_error=True)
except ValueError as err:
    if "special characters" in str(err):
        img = read_image(safe_ascii_path(path), raise_error=True)
    else:
        raise

Prevention

When it happens

Trigger: read_image(filename, raise_error=True) where the path contains non-ASCII/special characters that break cv2.imread (known cv2 issue on Windows and some locales), or the file content is truncated/corrupt so decoding raises ValueError.

Common situations: Windows paths with accented/CJK characters or emoji; images renamed with unusual bytes; files corrupted by interrupted transfers; case-sensitive path mismatches on Linux producing garbage reads.

Related errors


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