使用Google Cloud Vision API标注图片时遇503及属性错误求助
Hey there, let's work through the two problems you encountered when using the Google Cloud Vision API for image label detection. I'll break down each issue and show you the exact fixes.
1. Authentication Error: AttributeError & 503 ServiceUnavailable
The root cause here is how you're passing the service account key to ImageAnnotatorClient. The credentials parameter doesn't accept a string file path directly—it expects a valid Credentials object instead. When you pass a string, the client tries to call methods like before_request on it (which strings don't have), leading to the AttributeError, and that failure cascades into the 503 error because the API can't authenticate your request.
Correct Ways to Authenticate:
Option 1: Load the Credentials Object Explicitly
Use the service_account module to load your key file into a valid Credentials instance:
from google.cloud import vision from google.oauth2 import service_account # Replace with your actual key file path credentials = service_account.Credentials.from_service_account_file("/path/to/your/service-account-key.json") client = vision.ImageAnnotatorClient(credentials=credentials)
Option 2: Use an Environment Variable (Simpler for Production)
Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to your key file path. The client will automatically pick it up without needing to pass credentials explicitly:
import os from google.cloud import vision # Set the environment variable (you can also set this system-wide instead of in code) os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/service-account-key.json" # Initialize the client—no credentials parameter needed client = vision.ImageAnnotatorClient()
2. Image Type Mismatch: numpy.ndarray → bytes
Great call fixing this one! The vision.types.Image class requires raw bytes content, not the numpy array returned by cv2.imread. For reference, here's a clean way to handle the conversion:
import cv2 from google.cloud import vision # Read the image with cv2 image_cv = cv2.imread("/path/to/your/image.jpg") # Encode the numpy array to JPEG bytes _, img_encoded = cv2.imencode(".jpg", image_cv) image_bytes = img_encoded.tobytes() # Create the Vision API Image object image = vision.Image(content=image_bytes) # Run label detection response = client.label_detection(image=image) labels = response.label_annotations # Print out the results for label in labels: print(f"Label: {label.description}, Score: {label.score}")
Once you fix the authentication issue with either of the options above, your label detection should work without errors.
内容的提问来源于stack exchange,提问作者Stefano Pozzi

