{"record":{"id":"3f4a90896c2ac758","repo":"deepfakes/faceswap","slug":"error-while-reading-image-typeerror-filename","errorCode":null,"errorMessage":"Error while reading image (TypeError): '{filename}'. Original error message: {str(err)}","messagePattern":"Error while reading image \\(TypeError\\): '(.+?)'\\. Original error message: (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"lib/image.py","lineNumber":136,"sourceCode":"            # Just naively clip floating images to 0-1 for now\n            image = (np.clip(image, 0.0, 1.0) * 255.).astype(np.float32)\n\n        if image.dtype != np.uint8:\n            image = np.clip(image, 0, 255).astype(np.uint8)\n\n        if with_metadata:\n            metadata = png_read_meta(raw_file)\n            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","sourceCodeStart":118,"sourceCodeEnd":154,"githubUrl":"https://github.com/deepfakes/faceswap/blob/f530cb7508ae670f6474f8a7d9c4df94705cf96b/lib/image.py#L118-L154","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Rename/sanitize the file and path to plain ASCII (no accents, spaces, emoji) and retry","Verify the file opens in an image viewer or with PIL.Image.open(path).verify(); re-export or delete if corrupt","If sanitizing thousands of paths, write a normalization pass that maps old->new names and update the alignments file keys accordingly"],"exampleFix":"# before\nimg = read_image(\"C:/data/héllo wörld/000001.png\", raise_error=True)\n\n# after\nimport shutil, os\nos.rename(r\"C:\\data\\héllo wörld\", r\"C:\\data\\hello_world\")\nimg = read_image(\"C:/data/hello_world/000001.png\", raise_error=True)","handlingStrategy":"validation","validationCode":"import os, unicodedata, re\n\ndef safe_ascii_path(path):\n    name = unicodedata.normalize(\"NFKD\", os.path.basename(path))\n    name = name.encode(\"ascii\", \"ignore\").decode()\n    name = re.sub(r\"[^A-Za-z0-9_.-]\", \"_\", name)\n    return os.path.join(os.path.dirname(path), name or \"unnamed\")\n\n# verify decodability before read_image\nfrom PIL import Image\nassert Image.open(path).verify() is None or True","typeGuard":"def is_ascii_image_path(path: str) -> bool:\n    \"\"\"True when path has no non-ASCII chars that break cv2.imread.\"\"\"\n    return path.isascii()","tryCatchPattern":"try:\n    img = read_image(path, raise_error=True)\nexcept ValueError as err:\n    if \"special characters\" in str(err):\n        img = read_image(safe_ascii_path(path), raise_error=True)\n    else:\n        raise","preventionTips":["Keep dataset paths plain ASCII, especially on Windows","Verify images with PIL .verify() during dataset prep","Rename early and update alignments keys to match"],"tags":["faceswap","image-io","filename-encoding","corrupt-file","windows"],"backgroundTag":null,"analyzedSha":"f530cb7508ae670f6474f8a7d9c4df94705cf96b","analyzedAt":"2026-08-15T02:59:26.626Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}