Select Page

Image Analysis

Full Image Extraction Code

import os
import requests
import pandas as pd
from serpapi import GoogleSearch

# ✅ SerpApi Key
SERPAPI_API_KEY = "1c883402e26889d13bffd62479d91e1d66c8c4bb3d3f532013e64222c5e519ae"
print("All libraries imported successfully. Ready to proceed.")

# 🔍 Search SerpApi for image URLs
def search_images_serpapi(query_term, num_results=1000):
    image_urls = []
    page = 0

    while len(image_urls) < num_results:
        params = {
             "q": query_term,
            "engine": "google_images",
            "ijn": page,
            "api_key": SERPAPI_API_KEY,
            "tbs": "itp:photo,ic:color",  # photo type only, colour images
            "tbm": "isch",  # image search
        }

        search = GoogleSearch(params)
        results = search.get_dict()

        if "error" in results:
            print(f"❌ SerpApi error: {results['error']}")
            break

        images = results.get("images_results", [])
        if not images:
            break

        for item in images:
            if "original" in item:
                image_urls.append(item["original"])
                if len(image_urls) >= num_results:
                    break

        page += 1

    print(f"✅ {len(image_urls)} images found for: '{query_term}'")
    return pd.DataFrame(image_urls, columns=["image_url"])

# 💾 Download image files
def download_images(image_urls, save_dir):
    os.makedirs(save_dir, exist_ok=True)
    for i, url in enumerate(image_urls):
        try:
            response = requests.get(url, stream=True, timeout=5)
            response.raise_for_status()
            filename = f"image_{i}.jpg"
            filepath = os.path.join(save_dir, filename)
            with open(filepath, "wb") as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)
            print(f"📥 Downloaded: {filename}")
        except Exception as e:
            print(f"⚠️ Failed to download {url}: {e}")

# 🚀 Batch process multiple search terms
if __name__ == "__main__":

    search_terms = {
        "education": "Education -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "freedom": "Freedom -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "human_instinct": "Human instinct -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "instinct": "Instinct -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "nature": "Nature -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "play": "Play -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "safety": "Safety -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "connection":"Connection -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "Creativity": "Creativity -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
        "happiness": "Happiness -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -logo -text -quote -book -cover -title",
       
        
        "disconnection": "disconnection -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "sadness": "sadness -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "artificial": "artificial -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "danger": "danger -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "isolation": "isolation -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "standardisation": "standardisation -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "conformity": "conformity -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "social_media_addiction": "\"social media addiction\" -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "doomscrolling": "doomscrolling -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title",
        "technology_addiction": "\"technology addiction\" -movie -tv -series -logo -lyrics -song -album -music -watch -film -poster -text -quote -book -cover -title"
}

    images_per_term = 500

    for name, query in search_terms.items():
        print(f"\n🔎 Searching: {query}")
        df = search_images_serpapi(query, images_per_term)
        folder = f"{name}_images"
        print(f"💾 Saving to: {folder}")
        download_images(df["image_url"].tolist(), folder)

    print("\n✅ All searches complete.")



←→