Automated Image Dataset Generation with LMMs
Overview
This skill provides a scalable, reusable framework for automatically generating labeled image datasets using web scraping combined with Large Multimodal Models (LMMs) for metadata generation. The methodology addresses the challenge of manual data collection being resource-intensive, error-prone, and time-consuming.
Key Capabilities:
- Automated web image collection at scale (50,000+ images)
- LMM-powered metadata generation with ~95% accuracy
- Rule-based filtering for domain-specific categorization
- Structured output for object detection and classification tasks
When to Use This Skill
Use this skill when:
- Building custom image datasets for machine learning applications
- Collecting domain-specific images that aren't available in existing datasets
- Needing automated image labeling/metadata generation
- Working on object detection or image classification projects
- Manual annotation is too expensive or time-consuming
- Requiring large-scale training data for computer vision models
Core Workflow
Phase 1: Query Design and Planning
Define Target Categories:
- Identify specific objects/classes to collect
- Create hierarchical category structure if needed
- Example categories: beams, columns, trusses, steel frames
Design Search Queries:
# Generate diverse search queries
categories = ["structural steel beam", "steel column construction", "roof truss"]
query_variations = [
f"{cat} {mod}"
for cat in categories
for mod in ["photo", "site", "construction", "building"]
]
Set Collection Parameters:
- Target image count per category
- Image quality thresholds (resolution, format)
- Source diversity requirements
Phase 2: Web Scraping
Implement Multi-Source Scraping:
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
def scrape_images(query, num_images=1000):
"""
Scrape images from multiple sources:
- Google Images
- Bing Images
- Domain-specific sites
"""
images = []
# Use appropriate rate limiting
# Respect robots.txt
# Store source URLs for attribution
return images
Image Download and Storage:
def download_images(image_urls, output_dir):
"""
Download images with:
- Duplicate detection (hash-based)
- Format validation
- Resolution filtering
- Metadata preservation
"""
pass
Initial Filtering:
- Remove corrupted/invalid images
- Filter by minimum resolution (e.g., 224x224)
- Deduplicate using perceptual hashing
Phase 3: LMM-Based Metadata Generation
Configure LMM (Gemini Vision or equivalent):
import google.generativeai as genai
genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
model = genai.GenerativeModel('gemini-1.5-flash')
def generate_metadata(image_path, categories):
"""
Use LMM to analyze image and generate metadata
"""
image = PIL.Image.open(image_path)
prompt = f"""
Analyze this image and determine:
1. Does it contain any of these objects: {categories}?
2. If yes, which specific category?
3. Confidence level (high/medium/low)
4. Object location description (for detection tasks)
5. Image quality assessment
Return structured JSON response.
"""
response = model.generate_content([prompt, image])
return parse_response(response.text)
Batch Processing:
def process_dataset(image_dir, categories, batch_size=100):
"""
Process images in batches with:
- Rate limiting
- Error handling
- Progress tracking
- Checkpoint saving
"""
results = []
for batch in get_batches(image_dir, batch_size):
batch_results = [
generate_metadata(img, categories)
for img in batch
]
results.extend(batch_results)
save_checkpoint(results)
return results
Quality Metrics:
- Track LMM confidence scores
- Flag low-confidence predictions for review
- Calculate category distribution
Phase 4: Rule-Based Filtering
Apply Category Rules:
def filter_by_rules(metadata, rules):
"""
Apply domain-specific rules:
- Minimum confidence threshold (e.g., 0.8)
- Category-specific validation
- Cross-reference with search query
"""
filtered = []
for item in metadata:
if item['confidence'] >= rules['min_confidence']:
if validate_category(item, rules):
filtered.append(item)
return filtered
Handle Edge Cases:
- Multi-label images (multiple categories)
- Ambiguous classifications
- Partial object visibility
Phase 5: Dataset Finalization
Generate Dataset Structure:
dataset/
├── images/
│ ├── category_1/
│ ├── category_2/
│ └── ...
├── annotations/
│ ├── metadata.json
│ └── labels.csv
├── splits/
│ ├── train.txt
│ ├── val.txt
│ └── test.txt
└── README.md
Create Annotation Files:
def create_annotations(filtered_data, output_dir):
"""
Generate standard annotation formats:
- COCO format (for object detection)
- CSV with labels (for classification)
- YOLO format (if needed)
"""
pass
Split Dataset:
- Train/Val/Test split (typically 70/15/15)
- Stratified splitting by category
- Ensure no data leakage
Best Practices
Web Scraping
- Respect rate limits: 1-2 requests per second
- Rotate user agents: Avoid detection
- Use proxies: For large-scale collection
- Cache responses: Avoid redundant downloads
- Store source URLs: For attribution and verification
LMM Usage
- Use appropriate prompts: Be specific about expected output format
- Batch processing: Optimize API costs
- Handle API errors: Implement retry logic with exponential backoff
- Validate responses: Parse and validate JSON responses
Data Quality
- Verify sample manually: Check 100-200 random samples
- Calculate inter-annotator agreement: If using multiple LMMs
- Document accuracy metrics: Report precision/recall per category
- Version your dataset: Track changes over time
Legal & Ethical
- Check image licenses: Prefer CC-licensed content
- Respect robots.txt: Don't scrape disallowed pages
- Attribute sources: Maintain source URLs
- Consider privacy: Filter personal/sensitive content
Expected Results
Based on the original research:
- Collection scale: 50,000+ raw images
- After filtering: ~5% relevant images (domain-specific)
- Metadata accuracy: 94.8%
- Categories: Successfully identifies 5+ distinct categories
Integration with Other Skills
- scientific-schematics: Generate dataset visualization diagrams
- exploratory-data-analysis: Analyze dataset statistics
- pytorch: Train models on generated dataset
- matplotlib/seaborn: Visualize class distributions
Dependencies
# Core
pip install requests beautifulsoup4 selenium pillow
# LMM
pip install google-generativeai # or openai for GPT-4V
# Image processing
pip install imagehash opencv-python
# Dataset tools
pip install pandas scikit-learn
References
- Gharib, S., & Moselhi, O. (2025). Automated Image Dataset Generation Using Web Scraping and Large Multimodal Models for Construction Applications. ISARC 2025.
1---2name: automated-image-dataset-generation3description: Generate large-scale image datasets automatically using web scraping and Large Multimodal Models (LMMs) like Gemini Vision. This skill implements the methodology from the research paper "Automated Image Dataset Generation Using Web Scraping and Large Multimodal Models for Construction Applications" by Gharib & Moselhi. Achieves ~95% accuracy in metadata generation for image classification and object detection tasks.4license: MIT license5---67# Automated Image Dataset Generation with LMMs89## Overview1011This skill provides a scalable, reusable framework for automatically generating labeled image datasets using web scraping combined with Large Multimodal Models (LMMs) for metadata generation. The methodology addresses the challenge of manual data collection being resource-intensive, error-prone, and time-consuming.1213**Key Capabilities:**14- Automated web image collection at scale (50,000+ images)15- LMM-powered metadata generation with ~95% accuracy16- Rule-based filtering for domain-specific categorization17- Structured output for object detection and classification tasks1819## When to Use This Skill2021Use this skill when:22- Building custom image datasets for machine learning applications23- Collecting domain-specific images that aren't available in existing datasets24- Needing automated image labeling/metadata generation25- Working on object detection or image classification projects26- Manual annotation is too expensive or time-consuming27- Requiring large-scale training data for computer vision models2829## Core Workflow3031### Phase 1: Query Design and Planning32331. **Define Target Categories**:34 - Identify specific objects/classes to collect35 - Create hierarchical category structure if needed36 - Example categories: beams, columns, trusses, steel frames37382. **Design Search Queries**:39 ```python40 # Generate diverse search queries41 categories = ["structural steel beam", "steel column construction", "roof truss"]42 query_variations = [43 f"{cat} {mod}" 44 for cat in categories 45 for mod in ["photo", "site", "construction", "building"]46 ]47 ```48493. **Set Collection Parameters**:50 - Target image count per category51 - Image quality thresholds (resolution, format)52 - Source diversity requirements5354### Phase 2: Web Scraping55561. **Implement Multi-Source Scraping**:57 ```python58 import requests59 from bs4 import BeautifulSoup60 from selenium import webdriver61 62 def scrape_images(query, num_images=1000):63 """64 Scrape images from multiple sources:65 - Google Images66 - Bing Images67 - Domain-specific sites68 """69 images = []70 71 # Use appropriate rate limiting72 # Respect robots.txt73 # Store source URLs for attribution74 75 return images76 ```77782. **Image Download and Storage**:79 ```python80 def download_images(image_urls, output_dir):81 """82 Download images with:83 - Duplicate detection (hash-based)84 - Format validation85 - Resolution filtering86 - Metadata preservation87 """88 pass89 ```90913. **Initial Filtering**:92 - Remove corrupted/invalid images93 - Filter by minimum resolution (e.g., 224x224)94 - Deduplicate using perceptual hashing9596### Phase 3: LMM-Based Metadata Generation97981. **Configure LMM (Gemini Vision or equivalent)**:99 ```python100 import google.generativeai as genai101 102 genai.configure(api_key=os.environ['GOOGLE_API_KEY'])103 model = genai.GenerativeModel('gemini-1.5-flash')104 105 def generate_metadata(image_path, categories):106 """107 Use LMM to analyze image and generate metadata108 """109 image = PIL.Image.open(image_path)110 111 prompt = f"""112 Analyze this image and determine:113 1. Does it contain any of these objects: {categories}?114 2. If yes, which specific category?115 3. Confidence level (high/medium/low)116 4. Object location description (for detection tasks)117 5. Image quality assessment118 119 Return structured JSON response.120 """121 122 response = model.generate_content([prompt, image])123 return parse_response(response.text)124 ```1251262. **Batch Processing**:127 ```python128 def process_dataset(image_dir, categories, batch_size=100):129 """130 Process images in batches with:131 - Rate limiting132 - Error handling133 - Progress tracking134 - Checkpoint saving135 """136 results = []137 for batch in get_batches(image_dir, batch_size):138 batch_results = [139 generate_metadata(img, categories) 140 for img in batch141 ]142 results.extend(batch_results)143 save_checkpoint(results)144 return results145 ```1461473. **Quality Metrics**:148 - Track LMM confidence scores149 - Flag low-confidence predictions for review150 - Calculate category distribution151152### Phase 4: Rule-Based Filtering1531541. **Apply Category Rules**:155 ```python156 def filter_by_rules(metadata, rules):157 """158 Apply domain-specific rules:159 - Minimum confidence threshold (e.g., 0.8)160 - Category-specific validation161 - Cross-reference with search query162 """163 filtered = []164 for item in metadata:165 if item['confidence'] >= rules['min_confidence']:166 if validate_category(item, rules):167 filtered.append(item)168 return filtered169 ```1701712. **Handle Edge Cases**:172 - Multi-label images (multiple categories)173 - Ambiguous classifications174 - Partial object visibility175176### Phase 5: Dataset Finalization1771781. **Generate Dataset Structure**:179 ```180 dataset/181 ├── images/182 │ ├── category_1/183 │ ├── category_2/184 │ └── ...185 ├── annotations/186 │ ├── metadata.json187 │ └── labels.csv188 ├── splits/189 │ ├── train.txt190 │ ├── val.txt191 │ └── test.txt192 └── README.md193 ```1941952. **Create Annotation Files**:196 ```python197 def create_annotations(filtered_data, output_dir):198 """199 Generate standard annotation formats:200 - COCO format (for object detection)201 - CSV with labels (for classification)202 - YOLO format (if needed)203 """204 pass205 ```2062073. **Split Dataset**:208 - Train/Val/Test split (typically 70/15/15)209 - Stratified splitting by category210 - Ensure no data leakage211212## Best Practices213214### Web Scraping2151. **Respect rate limits**: 1-2 requests per second2162. **Rotate user agents**: Avoid detection2173. **Use proxies**: For large-scale collection2184. **Cache responses**: Avoid redundant downloads2195. **Store source URLs**: For attribution and verification220221### LMM Usage2221. **Use appropriate prompts**: Be specific about expected output format2232. **Batch processing**: Optimize API costs2243. **Handle API errors**: Implement retry logic with exponential backoff2254. **Validate responses**: Parse and validate JSON responses226227### Data Quality2281. **Verify sample manually**: Check 100-200 random samples2292. **Calculate inter-annotator agreement**: If using multiple LMMs2303. **Document accuracy metrics**: Report precision/recall per category2314. **Version your dataset**: Track changes over time232233### Legal & Ethical2341. **Check image licenses**: Prefer CC-licensed content2352. **Respect robots.txt**: Don't scrape disallowed pages2363. **Attribute sources**: Maintain source URLs2374. **Consider privacy**: Filter personal/sensitive content238239## Expected Results240241Based on the original research:242- **Collection scale**: 50,000+ raw images243- **After filtering**: ~5% relevant images (domain-specific)244- **Metadata accuracy**: 94.8%245- **Categories**: Successfully identifies 5+ distinct categories246247## Integration with Other Skills248249- **scientific-schematics**: Generate dataset visualization diagrams250- **exploratory-data-analysis**: Analyze dataset statistics251- **pytorch**: Train models on generated dataset252- **matplotlib/seaborn**: Visualize class distributions253254## Dependencies255256```bash257# Core258pip install requests beautifulsoup4 selenium pillow259260# LMM261pip install google-generativeai # or openai for GPT-4V262263# Image processing264pip install imagehash opencv-python265266# Dataset tools267pip install pandas scikit-learn268```269270## References271272- Gharib, S., & Moselhi, O. (2025). Automated Image Dataset Generation Using Web Scraping and Large Multimodal Models for Construction Applications. ISARC 2025.