使用tf.train.example遇TypeError:预期bytes却传入int值求助
Hey there, let's break down this issue you're facing. Even though you think you're passing a bytes type, the error clearly says the value 71 is an int when bytes were expected. Looking at your traceback, the problem happens in your _bytes_feature function when creating tf.train.BytesList(value=value)—so let's dig into why that's happening.
Common Causes & Fixes
1. Your image data isn't actually a bytes object
If img_data is a numpy array (like what you get from converting a PIL image), passing it directly to _bytes_feature will treat it as a sequence of integers (each pixel value is an int). You need to explicitly convert it to bytes:
# Assuming img_data is a numpy array img_data = img_data.tobytes() # Converts the array to a raw bytes object
2. Your _bytes_feature function isn't handling single bytes correctly
The tf.train.BytesList expects an iterable of bytes objects. If you're passing a single bytes value instead of a list containing that value, it might iterate over the bytes as individual integers (since bytes are iterable in Python). Fix your function to wrap single values in a list:
def _bytes_feature(value): # Handle EagerTensor if needed if isinstance(value, type(tf.constant(0))): value = value.numpy() # Wrap single bytes in a list for BytesList return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
3. You're reading the image in text mode instead of binary mode
If you're loading your image with open("image.jpg", "r"), you're reading it as text, which can mangle the data and lead to unexpected int values. Always use binary mode for images:
with open("your_image.jpg", "rb") as f: img_data = f.read() # This gives you a proper bytes object directly
Quick Debug Check
Before calling _bytes_feature(img_data), add these lines to verify what you're actually passing:
print(f"Type of img_data: {type(img_data)}") print(f"First 10 elements: {img_data[:10]}")
- If it's a bytes object, you'll see output like
b'\xff\xd8\xff\xe0\x00\x10JFIF' - If it's a numpy array or list, you'll see a sequence of integers like
[71, 72, 69, ...]
That should help you pinpoint exactly where the int values are sneaking in instead of bytes.
内容的提问来源于stack exchange,提问作者Tris Wang

