Google ML Engine Python脚本预测失败:图片解码错误求助
Hey there! Let’s dig into why your Python script is hitting that image decoding error when the gcloud command works perfectly. The issue almost always boils down to how your script is formatting the image data before sending it to the model—here’s how to fix it:
Common Fixes to Try
1. Ensure you’re reading the image in binary mode
gcloud handles file paths directly and reads images as raw bytes, but if your Python script uses text mode to open the image, it’ll corrupt the data. Always use rb mode when reading image files:
with open("your_image.jpg", "rb") as f: image_data = f.read()
2. Match the model’s expected input format
Most image models expect either base64-encoded bytes or raw byte data in the prediction payload. If your model was trained to accept base64 (common for Vertex AI/AI Platform models), encode the raw bytes like this:
import base64 encoded_image = base64.b64encode(image_data).decode("utf-8")
Then structure your payload to match the model’s input signature (adjust the key name if your model uses something like inputs instead of image_bytes):
payload = { "instances": [ {"image_bytes": {"b64": encoded_image}} ] }
3. Verify your request authentication & endpoint
Make sure your Python script is using a valid access token (same as your gcloud session). You can fetch one with gcloud auth print-access-token and include it in your request headers:
import requests response = requests.post( "https://us-central1-ml.googleapis.com/v1/projects/your-project-id/models/your-model:predict", headers={"Authorization": "Bearer YOUR_ACCESS_TOKEN"}, json=payload )
4. Double-check the image itself
Even if gcloud works, confirm your script is pointing to the exact same image file. Accidentally reading a corrupted or non-image file will trigger this error. You can quickly validate the image with Pillow:
from PIL import Image try: Image.open("your_image.jpg") print("Image is valid!") except Exception as e: print(f"Image is corrupted: {e}")
Example Working Script
Putting it all together, here’s a minimal script that mirrors how gcloud sends prediction requests:
import base64 import json import requests # Step 1: Read image correctly with open("test_image.png", "rb") as f: image_bytes = f.read() # Step 2: Encode and format payload encoded_image = base64.b64encode(image_bytes).decode("utf-8") payload = {"instances": [{"image_bytes": {"b64": encoded_image}}]} # Step 3: Send request (replace with your details) access_token = "YOUR_ACCESS_TOKEN" # Get via `gcloud auth print-access-token` endpoint = "https://us-central1-ml.googleapis.com/v1/projects/your-project/models/your-model:predict" response = requests.post( endpoint, headers={"Authorization": f"Bearer {access_token}"}, json=payload ) # Handle response if response.ok: print("Prediction results:", json.dumps(response.json(), indent=2)) else: print(f"Error: {response.status_code}\n{response.text}")
The key takeaway is to replicate how gcloud handles the image data—raw bytes formatted correctly for your model’s input signature. Once you align that, the decoding error should disappear.
内容的提问来源于stack exchange,提问作者Sam

