import os
import os
import random
import shutil
import pandas as pd
from google.cloud import vision
from google.oauth2 import service_account
# === CONFIG ===
base_path =
folder_names = [
"Connection_images", "Creativity_images", "Education_images", "freedom_images", "happiness_images",
"human_instinct_images", "instinct_images", "nature_images", "play_images", "safety_images",
"disconnection_images", "sadness_images", "artificial_images", "danger_images", "isolation_images",
"standardisation_images", "conformity_images", "social_media_addiction_images",
"doomscrolling_images", "technology_addiction_images"
]
image_folders = [os.path.join(base_path, folder) for folder in folder_names]
creds_path = os.path.join(base_path, "vision_credentials.json")
# Output paths
output_image_dir = os.path.join(base_path, "google_vision_calibration_images_selected")
output_csv_path = os.path.join(base_path, "google_vision_calibration_objects.csv")
num_images = 50
# Create output folders
os.makedirs(output_image_dir, exist_ok=True)
# === SETUP GOOGLE VISION CLIENT ===
def setup_vision_client(json_path):
credentials = service_account.Credentials.from_service_account_file(json_path)
return vision.ImageAnnotatorClient(credentials=credentials)
# === DETECT OBJECTS ===
def get_objects(image_path, client):
with open(image_path, "rb") as image_file:
content = image_file.read()
if not content:
print(f"⚠️ Skipping empty file: {image_path}")
return {}
image = vision.Image(content=content)
try:
response = client.annotate_image({
"image": image,
"features": [{"type_": vision.Feature.Type.OBJECT_LOCALIZATION}]
})
return {obj.name: round(obj.score, 4) for obj in response.localized_object_annotations}
except Exception as e:
print(f"❌ Error processing {image_path}: {e}")
return {}
# === SAMPLE IMAGES ACROSS ALL FOLDERS ===
def sample_images(folders, n):
all_images = []
for folder in folders:
if not os.path.exists(folder): continue
for fname in os.listdir(folder):
if fname.lower().endswith((".jpg", ".jpeg", ".png")):
full_path = os.path.join(folder, fname)
category = os.path.basename(folder).replace("_images", "")
all_images.append({
"category": category,
"image_name": fname,
"image_path": full_path
})
return random.sample(all_images, min(n, len(all_images)))
# === MAIN EXECUTION ===
if __name__ == "__main__":
client = setup_vision_client(creds_path)
sampled = sample_images(image_folders, num_images)
print(f"📸 Sampled {len(sampled)} images from {len(image_folders)} folders")
all_rows = []
for item in sampled:
category = item["category"]
image_name = item["image_name"]
print(f"🔍 {category}: {image_name}")
result = get_objects(item["image_path"], client)
# Create category folder inside output folder
category_dir = os.path.join(output_image_dir, category)
os.makedirs(category_dir, exist_ok=True)
# Save image with same name into category subfolder
new_image_path = os.path.join(category_dir, image_name)
shutil.copy2(item["image_path"], new_image_path)
row = {
"image_name": image_name,
"category": category,
"image_path": os.path.abspath(new_image_path),
"image_link": f'=HYPERLINK("{os.path.abspath(new_image_path)}", "Open Image")',
"analysis_method": "Google Vision Calibration"
}
row.update(result)
all_rows.append(row)
# === SAVE COMBINED CSV ===
df = pd.DataFrame(all_rows).fillna(0.0)
base_cols = ["image_name", "category", "image_path", "image_link", "analysis_method"]
label_cols = [col for col in df.columns if col not in base_cols]
df = df[base_cols + label_cols]
df.to_csv(output_csv_path, index=False)
print(f"\n✅ CSV saved to: {output_csv_path}")
print(f"📁 Calibration images saved in folders at: {output_image_dir}")