WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError
Image '{}' format not JPEG
Error message
Image '{}' format not JPEG What it means
VOCDataSet.__getitem__ opens the image named in the annotation XML and requires its format to be exactly 'JPEG' (PIL's format attribute). Any other format — PNG, BMP, GIF, MPO, or a JPEG whose PIL format reads differently — raises ValueError with the image path. The code assumes a standard VOC2012 dataset where all images are JPEG.
Source
Thrown at pytorch_object_detection/faster_rcnn/my_dataset.py:72
with open(json_file, 'r') as f:
self.class_dict = json.load(f)
self.transforms = transforms
def __len__(self):
return len(self.xml_list)
def __getitem__(self, idx):
# read xml
xml_path = self.xml_list[idx]
with open(xml_path) as fid:
xml_str = fid.read()
xml = etree.fromstring(xml_str)
data = self.parse_xml_to_dict(xml)["annotation"]
img_path = os.path.join(self.img_root, data["filename"])
image = Image.open(img_path)
if image.format != "JPEG":
raise ValueError("Image '{}' format not JPEG".format(img_path))
boxes = []
labels = []
iscrowd = []
assert "object" in data, "{} lack of object information.".format(xml_path)
for obj in data["object"]:
xmin = float(obj["bndbox"]["xmin"])
xmax = float(obj["bndbox"]["xmax"])
ymin = float(obj["bndbox"]["ymin"])
ymax = float(obj["bndbox"]["ymax"])
# 进一步检查数据,有的标注信息中可能有w或h为0的情况,这样的数据会导致计算回归loss为nan
if xmax <= xmin or ymax <= ymin:
print("Warning: in '{}' xml, there are some bbox w/h <=0".format(xml_path))
continue
boxes.append([xmin, ymin, xmax, ymax])
labels.append(self.class_dict[obj["name"]])View on GitHub (pinned to 1ec3fe6f37)
Solutions
- Convert all dataset images to JPEG: e.g. `for f in *.png; do convert $f ${f%.png}.jpg; done` and update the XML filenames.
- Check data['filename'] in the failing XML matches an actual .jpg file with JPEG content.
- Re-encode with PIL: Image.open(p).convert('RGB').save(p, 'JPEG').
- Remove or fix non-conforming samples from the XML/ImageSets lists.
- Relax the check (image.convert('RGB')) if you intentionally support other formats.
Example fix
# before
image = Image.open(img_path)
if image.format != "JPEG":
raise ValueError(...)
# after
image = Image.open(img_path)
if image.format != "JPEG":
image = image.convert("RGB") # tolerate PNG/BMP inputs Defensive patterns
Strategy: validation
Validate before calling
from PIL import Image
img_path = os.path.join(self.img_root, data['filename'])
with Image.open(img_path) as im:
assert im.format == 'JPEG', f"{img_path} is {im.format}, convert to JPEG" Type guard
def is_jpeg(path: str) -> bool:
try:
with Image.open(path) as im:
return im.format == 'JPEG'
except Exception:
return False Try / catch
try:
image, target = dataset[i]
except ValueError as e:
print(f'Skipping non-JPEG sample: {e}')
continue Prevention
- Audit dataset images for PNG/BMP files renamed .jpg
- Re-encode all images with PIL to JPEG during dataset preparation
- Keep XML <filename> entries in sync with actual files
- Convert to RGB in __getitem__ if you must tolerate other formats
When it happens
Trigger: The XML annotation's <filename> points to a non-JPEG file (e.g. image.png/image.bmp), a file with a wrong/misleading name, or a corrupted image PIL cannot decode as JPEG.
Common situations: Mixing a custom dataset into VOC layout, images converted/re-encoded with wrong extensions, downloading images that are PNG but renamed .jpg, or camera images with MPO format.
Related errors
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
- image: {} isn't RGB mode.
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/80b4273993a477b6.
Report an issue: GitHub.