如何用Python获取Google图片搜索结果的平均颜色?
Sure thing! You can absolutely calculate the average color of Google Image Search results with Python—let's walk through how to do this for a query like "banana" (which should land us in that warm yellow range).
We’ll break this into three core steps: fetching image URLs from Google Images, loading those images, and calculating their average color. We’ll cover both a compliant API approach (best for long-term reliability) and a web-scraping method (note: Google’s page structure changes often, and scraping may violate their terms, so use cautiously).
1. Fetch Image URLs (Google Custom Search API)
The most reliable way is to use Google’s official Custom Search API—this avoids anti-scraping blocks and is fully allowed. You’ll need to grab an API key and a custom search engine ID first (the free tier has limited requests, but it’s perfect for small projects).
Here’s how to fetch image URLs with the API:
import requests API_KEY = "your_api_key_here" SEARCH_ENGINE_ID = "your_search_engine_id_here" QUERY = "banana" NUM_IMAGES = 10 # Adjust how many images you want to sample def fetch_image_urls(query, api_key, engine_id, num_images): url = f"https://www.googleapis.com/customsearch/v1?q={query}&cx={engine_id}&searchType=image&key={api_key}&num={num_images}" response = requests.get(url) results = response.json() return [item["link"] for item in results.get("items", [])] image_urls = fetch_image_urls(QUERY, API_KEY, SEARCH_ENGINE_ID, NUM_IMAGES)
2. Load Images & Calculate Average Color
Once you have the URLs, use Pillow (Python Imaging Library) to load images and compute their average color. We’ll convert to the HSV color space to focus on hue—this is way better for identifying "yellow" than raw RGB averages, since RGB can mix into muddy, unrecognizable tones.
First, install Pillow if you haven’t:
pip install pillow
Then the code to calculate average hue (which maps directly to color tone):
from PIL import Image import requests from io import BytesIO import numpy as np def get_average_hue(image_url): try: # Fetch image from URL without saving locally response = requests.get(image_url, timeout=5) img = Image.open(BytesIO(response.content)).convert("HSV") # Resize image to speed up calculation (optional but recommended) img_small = img.resize((10, 10)) hsv_data = np.array(img_small) # Calculate average hue (H channel is first in HSV) average_hue = np.mean(hsv_data[:, :, 0]) return average_hue except Exception as e: print(f"Failed to process {image_url}: {e}") return None # Calculate average hue across all valid images hues = [h for h in [get_average_hue(url) for url in image_urls] if h is not None] if hues: overall_average_hue = np.mean(hues) print(f"Average hue for '{QUERY}' images: {overall_average_hue:.2f}") # Map hue to color description (yellow is roughly 20-60 degrees in HSV) if 20 <= overall_average_hue <= 60: print("This corresponds to a yellow/golden tone!") else: print(f"Color tone based on hue: {overall_average_hue}") else: print("No valid images processed.")
3. Web Scraping Alternative (Use Cautiously)
If you don’t want to use the API, you can scrape Google Images directly, but keep in mind Google regularly updates their page structure, and scraping may violate their Terms of Service. Here’s a basic example using requests and BeautifulSoup:
import requests from bs4 import BeautifulSoup def scrape_image_urls(query, num_images=10): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } url = f"https://www.google.co.uk/search?q={query}&tbm=isch" response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # Extract image URLs (note: this selector may break if Google updates their page) image_elements = soup.select("img.rg_i") image_urls = [] for elem in image_elements[:num_images]: img_url = elem.get("data-src") or elem.get("src") if img_url: image_urls.append(img_url) return image_urls # Use the same get_average_hue function from step 2 image_urls = scrape_image_urls("banana") # ... rest of the color calculation code ...
Key Notes:
- HSV is your friend: Hue directly tells you the color’s position on the color wheel, making it far more reliable for identifying "yellow" than mixing RGB values.
- API > Scraping: The Custom Search API is the way to go for production code; scraping is only suitable for quick, non-commercial tests.
- Error handling matters: Always add try/except blocks to handle broken links, timeouts, or images that can’t be loaded.
内容的提问来源于stack exchange,提问作者frenchie1980

