help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
satellite-images
RSK World
satellite-images
Satellite Images Dataset - Land Cover Classification + Building Detection + Remote Sensing + Geospatial Analysis
satellite-images
  • __pycache__
  • data
  • visualizations
  • .gitignore780 B
  • ADVANCED_FEATURES.md7.2 KB
  • ATTRIBUTION.md1.5 KB
  • DATA_SUMMARY.md3.9 KB
  • DOWNLOAD_REAL_DATA_GUIDE.md3.4 KB
  • ERROR_FIXES_SUMMARY.md3.2 KB
  • GITHUB_RELEASE_INSTRUCTIONS.md4.9 KB
  • LICENSE1.2 KB
  • PROJECT_INFO.md3 KB
  • QUICK_DOWNLOAD_GUIDE.md2.1 KB
  • QUICK_START_ADVANCED.md2 KB
  • README.md8.1 KB
  • RELEASE_NOTES_v1.0.0.md7.1 KB
  • advanced_example.py11 KB
  • advanced_processing.py17.3 KB
  • advanced_visualization.py15.5 KB
  • batch_processing.py11.9 KB
  • batch_processor.py10.8 KB
  • check_errors.py6.9 KB
  • config.py1.1 KB
  • create_placeholder_image.py3.5 KB
  • create_sample_images.py5.3 KB
  • data_loader.py6 KB
  • download_real_images.py5 KB
  • download_real_satellite_data.py8.4 KB
  • download_with_landsatxplore.py4.6 KB
  • download_with_sentinelsat.py6 KB
  • enhanced_real_image_downloader.py17.8 KB
  • example_usage.py4.3 KB
  • generate_sample_data.py7.2 KB
  • get_real_satellite_data.py9.6 KB
  • index.html18.5 KB
  • ml_features.py11.8 KB
  • ml_integration.py13.6 KB
  • process_images.py7 KB
  • real_image_downloader.py15.7 KB
  • requirements.txt632 B
  • requirements_download.txt474 B
  • satellite-images.png2.6 MB
  • setup.py1.6 KB
  • visualize.py5.8 KB
.gitignoreADVANCED_FEATURES.mdlogo.pngLICENSEml_features.pydatabase.pycreate_sample_images.py
.gitignore
Raw Download
Find: Go to:
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
ENV/
env/
.venv

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Project specific
*.zip
*.tar.gz
*.log
temp/
output/
*.npy
*.npz

# Keep data structure but ignore large files
data/images/*.png
data/images/*.tif
data/images/*.tiff
!data/images/.gitkeep

# Visualizations (can be regenerated)
visualizations/*.png
visualizations/*.jpg
!visualizations/.gitkeep

# Environment variables
.env
.env.local

# Jupyter
.ipynb_checkpoints/
*.ipynb

# Testing
.pytest_cache/
.coverage
htmlcov/
72 lines•780 B
text
ADVANCED_FEATURES.md
Raw Download

ADVANCED_FEATURES.md

# Advanced Features Documentation

## Overview

This document describes all the advanced features added to the Satellite Image Dataset project.

Created by: RSK World (https://rskworld.in)

## New Modules

### 1. `advanced_processing.py`
Advanced image processing capabilities:

- **Edge Detection**: Canny, Sobel, Laplacian, Scharr methods
- **Image Segmentation**: Watershed, SLIC, Felzenszwalb, Quickshift
- **Feature Extraction**:
- HOG (Histogram of Oriented Gradients)
- LBP (Local Binary Pattern)
- GLCM (Gray-Level Co-occurrence Matrix)
- **Image Enhancement**: CLAHE, histogram equalization, gamma correction, unsharp masking
- **Noise Reduction**: Gaussian, bilateral, median, non-local means
- **Histogram Analysis**: Comprehensive statistical analysis

### 2. `ml_integration.py`
Machine learning integration:

- **Feature Extraction for ML**: Patch-based feature extraction
- **Land Cover Classification**: Random Forest classifier training and prediction
- **Building Detection**: Simple building detection using image processing
- **Change Detection**: Compare two images and detect changes
- **NDVI Extraction**: Normalized Difference Vegetation Index calculation
- **Training Dataset Creation**: Utilities for creating ML-ready datasets

### 3. `enhanced_real_image_downloader.py`
Real satellite image downloading:

- **Planetary Computer**: Download Sentinel-2 images (no credentials needed)
- **USGS EarthExplorer**: Download Landsat data (requires free account)
- **Copernicus Hub**: Download Sentinel-2 data (requires free account)
- **Multiple Locations**: Predefined locations worldwide
- **Metadata Extraction**: Automatic metadata saving

### 4. `advanced_visualization.py`
Advanced visualization tools:

- **Statistical Visualization**: Comprehensive statistics dashboard
- **3D Surface Plots**: 3D visualization of image surfaces
- **Comparison Views**: Side-by-side image comparison
- **Time Series Visualization**: Visualize images over time
- **Overlay Visualization**: Buildings and regions overlaid on images
- **Interactive Dashboards**: Comprehensive data dashboards

### 5. `batch_processing.py`
Batch processing and augmentation:

- **Batch Processing**: Parallel processing of multiple images
- **Image Augmentation**:
- Horizontal/vertical flipping
- Rotation
- Brightness/contrast adjustment
- Noise addition
- Cropping
- Scaling
- **Export Utilities**: NumPy export, metadata export, manifest creation

### 6. `advanced_example.py`
Comprehensive example demonstrating all features.

## Usage Examples

### Advanced Processing

```python
from advanced_processing import AdvancedImageProcessor

processor = AdvancedImageProcessor()

# Edge detection
edges = processor.detect_edges(image, method='canny')

# Segmentation
segmented, props = processor.segment_image(image, method='slic')

# Extract all features
features = processor.extract_all_features(image)
```

### ML Integration

```python
from ml_integration import SatelliteMLProcessor

ml = SatelliteMLProcessor()

# Building detection
buildings = ml.detect_buildings_simple(image)

# NDVI
ndvi = ml.extract_ndvi(image)

# Change detection
change_map, stats = ml.detect_changes(img1, img2)
```

### Real Image Download

```python
from enhanced_real_image_downloader import EnhancedRealImageDownloader

downloader = EnhancedRealImageDownloader()

# Download from Planetary Computer (no credentials)
files = downloader.download_sample_real_images(num_images=10)
```

### Advanced Visualization

```python
from advanced_visualization import AdvancedVisualizer

viz = AdvancedVisualizer()

# Statistics
viz.visualize_statistics(image, save_path='stats.png')

# 3D plot
viz.visualize_3d_surface(image, save_path='3d.png')

# Dashboard
viz.create_dashboard(image, features, metadata)
```

### Batch Processing

```python
from batch_processing import BatchProcessor, ImageAugmenter

# Augmentation
augmenter = ImageAugmenter()
augmented = augmenter.augment_image(image, ['flip_horizontal', 'brightness'])

# Batch processing
processor = BatchProcessor(num_workers=4)
results = processor.process_batch(image_paths, process_func)
```

## Installation

Install all dependencies:

```bash
pip install -r requirements.txt
```

For real image downloading (optional):

```bash
pip install pystac-client planetary-computer requests
```

## Running Examples

Run the comprehensive example:

```bash
python advanced_example.py
```

This will demonstrate all advanced features with sample data.

## File Structure

```
satellite-images/
├── advanced_processing.py # Advanced image processing
├── ml_integration.py # ML integration
├── enhanced_real_image_downloader.py # Real image downloading
├── advanced_visualization.py # Advanced visualization
├── batch_processing.py # Batch processing & augmentation
├── advanced_example.py # Comprehensive example
├── data_loader.py # Original data loader
├── process_images.py # Original image processor
├── visualize.py # Original visualization
└── requirements.txt # Updated dependencies
```

## Dependencies

### Core (Required)
- numpy
- opencv-python
- rasterio
- matplotlib
- pillow
- scikit-image
- scikit-learn
- seaborn
- scipy
- tqdm

### Optional (for real image downloading)
- pystac-client
- planetary-computer
- landsatxplore
- sentinelsat
- earthengine-api

## Features Summary

| Feature | Module | Description |
|---------|--------|-------------|
| Edge Detection | advanced_processing | Multiple edge detection algorithms |
| Segmentation | advanced_processing | Image segmentation methods |
| Feature Extraction | advanced_processing | HOG, LBP, GLCM features |
| ML Classification | ml_integration | Land cover classification |
| Building Detection | ml_integration | Automated building detection |
| Change Detection | ml_integration | Compare images over time |
| NDVI Extraction | ml_integration | Vegetation index calculation |
| Real Image Download | enhanced_real_image_downloader | Download from multiple sources |
| 3D Visualization | advanced_visualization | 3D surface plots |
| Statistical Analysis | advanced_visualization | Comprehensive statistics |
| Batch Processing | batch_processing | Parallel image processing |
| Data Augmentation | batch_processing | Multiple augmentation methods |

## Performance

- **Batch Processing**: Uses ThreadPoolExecutor for parallel processing
- **Feature Extraction**: Optimized for large images
- **Visualization**: Efficient plotting with matplotlib
- **ML Processing**: Uses scikit-learn for fast training

## Notes

- Real image downloading requires internet connection
- Some features require additional packages (see requirements.txt)
- ML models can be trained on your own data
- All modules include error handling and examples

## Support

For questions or issues:
- Website: https://rskworld.in
- Email: help@rskworld.in
- Phone: +91 93305 39277

---

*Created by RSK World - https://rskworld.in*

LICENSE
Raw Download
Find: Go to:
MIT License

Copyright (c) 2024 RSK World

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

---

Created by: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277

30 lines•1.2 KB
text
ml_features.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Satellite Image Dataset - Machine Learning Features
Created by: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277

Machine learning utilities including:
- Feature extraction
- Classification helpers
- Model training utilities
- Prediction functions
"""

import numpy as np
from typing import Dict, List, Tuple, Optional
from pathlib import Path
import json
from sklearn.feature_extraction import image as skimage_feature
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import cv2


class MLFeatureExtractor:
    """
    Machine learning feature extraction for satellite images.
    Created by: RSK World (https://rskworld.in)
    """
    
    def __init__(self):
        """Initialize the feature extractor."""
        self.scaler = StandardScaler()
        self.pca = None
    
    def extract_handcrafted_features(self, image: np.ndarray) -> Dict:
        """
        Extract handcrafted features from satellite image.
        
        Args:
            image: Input image array
            
        Returns:
            Dictionary of extracted features
        """
        features = {}
        
        # Basic statistics
        features['mean'] = float(np.mean(image))
        features['std'] = float(np.std(image))
        features['min'] = float(np.min(image))
        features['max'] = float(np.max(image))
        features['median'] = float(np.median(image))
        
        # Color statistics (if multi-channel)
        if len(image.shape) == 3:
            for i in range(image.shape[2]):
                features[f'channel_{i}_mean'] = float(np.mean(image[:, :, i]))
                features[f'channel_{i}_std'] = float(np.std(image[:, :, i]))
        
        # Texture features
        if len(image.shape) == 3:
            gray = np.mean(image, axis=2)
        else:
            gray = image
        
        # Calculate gradients
        grad_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
        grad_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
        gradient_magnitude = np.sqrt(grad_x**2 + grad_y**2)
        
        features['gradient_mean'] = float(np.mean(gradient_magnitude))
        features['gradient_std'] = float(np.std(gradient_magnitude))
        features['gradient_max'] = float(np.max(gradient_magnitude))
        
        # Histogram features
        hist, _ = np.histogram(gray.flatten(), bins=32, range=(0, 1))
        hist = hist / hist.sum()  # Normalize
        features['histogram_entropy'] = float(-np.sum(hist[hist > 0] * np.log2(hist[hist > 0])))
        features['histogram_skewness'] = float(self._calculate_skewness(hist))
        features['histogram_kurtosis'] = float(self._calculate_kurtosis(hist))
        
        # Local binary pattern-like features
        features['local_variance'] = float(np.var(cv2.GaussianBlur(gray, (5, 5), 0)))
        
        return features
    
    def _calculate_skewness(self, data: np.ndarray) -> float:
        """Calculate skewness."""
        mean = np.mean(data)
        std = np.std(data)
        if std == 0:
            return 0.0
        return float(np.mean(((data - mean) / std) ** 3))
    
    def _calculate_kurtosis(self, data: np.ndarray) -> float:
        """Calculate kurtosis."""
        mean = np.mean(data)
        std = np.std(data)
        if std == 0:
            return 0.0
        return float(np.mean(((data - mean) / std) ** 4)) - 3.0
    
    def extract_patch_features(self, image: np.ndarray, patch_size: int = 32, 
                               stride: int = 16) -> np.ndarray:
        """
        Extract features from image patches.
        
        Args:
            image: Input image
            patch_size: Size of patches
            stride: Stride for patch extraction
            
        Returns:
            Array of patch features
        """
        if len(image.shape) == 3:
            gray = np.mean(image, axis=2)
        else:
            gray = image
        
        patches = skimage_feature.extract_patches_2d(gray, (patch_size, patch_size))
        
        # Extract features for each patch
        patch_features = []
        for patch in patches:
            features = [
                np.mean(patch),
                np.std(patch),
                np.var(patch),
                np.min(patch),
                np.max(patch)
            ]
            patch_features.append(features)
        
        return np.array(patch_features)
    
    def extract_deep_features(self, image: np.ndarray, method: str = 'histogram') -> np.ndarray:
        """
        Extract deep learning-style features.
        
        Args:
            image: Input image
            method: Feature extraction method
            
        Returns:
            Feature vector
        """
        if method == 'histogram':
            # Multi-scale histogram features
            features = []
            for scale in [1, 2, 4]:
                scaled = cv2.resize(image, 
                                   (image.shape[1] // scale, image.shape[0] // scale))
                if len(scaled.shape) == 3:
                    for c in range(scaled.shape[2]):
                        hist, _ = np.histogram(scaled[:, :, c].flatten(), bins=16)
                        features.extend(hist / hist.sum())
                else:
                    hist, _ = np.histogram(scaled.flatten(), bins=16)
                    features.extend(hist / hist.sum())
            return np.array(features)
        
        elif method == 'pca':
            # PCA-based features
            if len(image.shape) == 3:
                data = image.reshape(-1, image.shape[2])
            else:
                data = image.reshape(-1, 1)
            
            if self.pca is None:
                self.pca = PCA(n_components=50)
                data_scaled = self.scaler.fit_transform(data)
                self.pca.fit(data_scaled)
            
            data_scaled = self.scaler.transform(data)
            features = self.pca.transform(data_scaled)
            return features.mean(axis=0)  # Average over spatial dimensions
        
        else:
            # Default: flatten and sample
            if len(image.shape) == 3:
                flat = image.reshape(-1, image.shape[2])
            else:
                flat = image.reshape(-1, 1)
            
            # Sample features
            indices = np.linspace(0, len(flat) - 1, 100, dtype=int)
            return flat[indices].flatten()
    
    def cluster_image(self, image: np.ndarray, n_clusters: int = 5) -> Tuple[np.ndarray, np.ndarray]:
        """
        Cluster image pixels into regions.
        
        Args:
            image: Input image
            n_clusters: Number of clusters
            
        Returns:
            Tuple of (clustered image, cluster centers)
        """
        if len(image.shape) == 3:
            data = image.reshape(-1, image.shape[2])
        else:
            data = image.reshape(-1, 1)
        
        # Normalize
        data_scaled = self.scaler.fit_transform(data)
        
        # K-means clustering
        kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
        labels = kmeans.fit_predict(data_scaled)
        
        # Reshape labels
        clustered = labels.reshape(image.shape[:2])
        
        return clustered, kmeans.cluster_centers_
    
    def classify_land_cover(self, image: np.ndarray, 
                           feature_vector: Optional[np.ndarray] = None) -> Dict:
        """
        Simple land cover classification based on features.
        
        Args:
            image: Input image
            feature_vector: Optional pre-computed feature vector
            
        Returns:
            Classification results dictionary
        """
        if feature_vector is None:
            features = self.extract_handcrafted_features(image)
            feature_vector = np.array(list(features.values()))
        
        # Simple rule-based classification (can be replaced with trained model)
        if len(image.shape) == 3:
            mean_values = np.mean(image, axis=(0, 1))
        else:
            mean_values = np.array([np.mean(image)])
        
        # Classify based on color characteristics
        classifications = []
        confidences = []
        
        # Water (blue/dark)
        if mean_values[0] < 0.3 and len(mean_values) > 2:
            classifications.append("water")
            confidences.append(0.7)
        
        # Vegetation (green)
        if len(mean_values) > 1 and mean_values[1] > 0.4:
            classifications.append("vegetation")
            confidences.append(0.8)
        
        # Urban (bright, high variance)
        if np.mean(mean_values) > 0.5 and np.std(image) > 0.2:
            classifications.append("urban")
            confidences.append(0.75)
        
        # Barren (brown/yellow)
        if len(mean_values) > 2 and mean_values[0] > 0.4 and mean_values[1] < 0.4:
            classifications.append("barren")
            confidences.append(0.7)
        
        if not classifications:
            classifications.append("unknown")
            confidences.append(0.5)
        
        return {
            'classes': classifications,
            'confidences': confidences,
            'primary_class': classifications[0],
            'primary_confidence': confidences[0]
        }


class ModelTrainer:
    """
    Helper class for training ML models on satellite images.
    Created by: RSK World (https://rskworld.in)
    """
    
    @staticmethod
    def prepare_training_data(images: List[np.ndarray], 
                             labels: List[str],
                             feature_extractor: MLFeatureExtractor) -> Tuple[np.ndarray, np.ndarray]:
        """
        Prepare training data from images and labels.
        
        Args:
            images: List of image arrays
            labels: List of label strings
            feature_extractor: Feature extractor instance
            
        Returns:
            Tuple of (feature matrix, label array)
        """
        features_list = []
        labels_list = []
        
        for image, label in zip(images, labels):
            features = feature_extractor.extract_handcrafted_features(image)
            feature_vector = np.array(list(features.values()))
            features_list.append(feature_vector)
            labels_list.append(label)
        
        X = np.array(features_list)
        y = np.array(labels_list)
        
        return X, y


def example_usage():
    """Example usage of ML features."""
    print("Machine Learning Features - Example")
    print("Created by: RSK World (https://rskworld.in)")
    print("-" * 50)
    
    extractor = MLFeatureExtractor()
    
    # Create sample image
    sample_image = np.random.rand(256, 256, 3).astype(np.float32)
    
    # Extract handcrafted features
    features = extractor.extract_handcrafted_features(sample_image)
    print(f"Extracted {len(features)} features")
    print(f"Sample features: mean={features['mean']:.3f}, std={features['std']:.3f}")
    
    # Classify land cover
    classification = extractor.classify_land_cover(sample_image)
    print(f"Classification: {classification['primary_class']} "
          f"(confidence: {classification['primary_confidence']:.2f})")
    
    # Cluster image
    clustered, centers = extractor.cluster_image(sample_image, n_clusters=5)
    print(f"Clustered image shape: {clustered.shape}")
    print(f"Number of cluster centers: {len(centers)}")
    
    print("\nML features example completed!")


if __name__ == "__main__":
    example_usage()

347 lines•11.8 KB
python
create_sample_images.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Create Sample Satellite Images
Created by: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277

This script creates sample satellite images matching the annotation data.
"""

from PIL import Image, ImageDraw
import numpy as np
from pathlib import Path
import json


def hex_to_rgb(hex_color):
    """Convert hex color to RGB tuple."""
    hex_color = hex_color.lstrip('#')
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))


def create_satellite_image(image_id: str, labels_path: str = None, 
                          size: tuple = (512, 512)) -> Image.Image:
    """
    Create a sample satellite image based on label data.
    Created by: RSK World (https://rskworld.in)
    
    Args:
        image_id: Image identifier
        labels_path: Path to labels JSON file (optional)
        size: Image size (width, height)
    """
    width, height = size
    
    # Create base image with sky/water gradient (blue tones)
    img = Image.new('RGB', size, color='#1a4d80')
    draw = ImageDraw.Draw(img)
    
    # Create gradient background
    for y in range(height):
        r = int(26 + (y / height) * 30)
        g = int(77 + (y / height) * 40)
        b = int(128 + (y / height) * 50)
        color = (r, g, b)
        draw.line([(0, y), (width, y)], fill=color)
    
    # Color mapping for land cover classes
    class_colors = {
        'water': '#1e3a5f',
        'forest': '#2d5016',
        'urban': '#555555',
        'agriculture': '#8b7355',
        'barren': '#d4a574',
        'grassland': '#6b8e23'
    }
    
    # If labels file exists, use it to draw regions
    if labels_path and Path(labels_path).exists():
        with open(labels_path, 'r') as f:
            labels = json.load(f)
        
        # Draw regions from labels
        for region in labels.get('regions', []):
            class_name = region.get('class', '')
            polygon = region.get('polygon', [])
            
            if polygon and class_name in class_colors:
                # Convert polygon to flat list for PIL
                flat_polygon = [coord for point in polygon for coord in point]
                color = hex_to_rgb(class_colors[class_name])
                
                # Draw filled polygon
                draw.polygon(flat_polygon, fill=color, outline=None)
                
                # Add some texture/variation
                for i in range(3):
                    offset_x = np.random.randint(-5, 5)
                    offset_y = np.random.randint(-5, 5)
                    textured_polygon = [[p[0] + offset_x, p[1] + offset_y] for p in polygon]
                    flat_textured = [coord for point in textured_polygon for coord in point]
                    darker_color = tuple(max(0, c - 20) for c in color)
                    draw.polygon(flat_textured, fill=darker_color, outline=None)
    else:
        # Create random regions if no labels
        classes = ['water', 'forest', 'urban', 'agriculture', 'barren', 'grassland']
        for _ in range(5):
            class_name = np.random.choice(classes)
            x = np.random.randint(50, width - 100)
            y = np.random.randint(50, height - 100)
            w = np.random.randint(80, 150)
            h = np.random.randint(80, 150)
            
            color = hex_to_rgb(class_colors.get(class_name, '#555555'))
            draw.rectangle([x, y, x + w, y + h], fill=color)
    
    # Add some noise/texture to make it look more realistic
    pixels = np.array(img)
    noise = np.random.randint(-10, 10, pixels.shape, dtype=np.int16)
    pixels = np.clip(pixels.astype(np.int16) + noise, 0, 255).astype(np.uint8)
    img = Image.fromarray(pixels)
    
    return img


def create_all_sample_images():
    """
    Create sample images for all sample data files.
    Created by: RSK World (https://rskworld.in)
    """
    images_dir = Path("data/images")
    labels_dir = Path("data/labels")
    images_dir.mkdir(parents=True, exist_ok=True)
    
    print("Creating sample satellite images...")
    print("Created by: RSK World (https://rskworld.in)")
    print("-" * 50)
    
    # Find all label files
    label_files = list(labels_dir.glob("sample_*.json"))
    
    if not label_files:
        print("No label files found. Creating default sample images...")
        # Create at least 3 sample images
        for i in range(1, 4):
            image_id = f"sample_{i:03d}"
            img = create_satellite_image(image_id, size=(512, 512))
            output_path = images_dir / f"{image_id}.png"
            img.save(output_path, 'PNG')
            print(f"[OK] Created: {output_path}")
    else:
        # Create images based on label files
        for label_file in sorted(label_files):
            image_id = label_file.stem
            img = create_satellite_image(image_id, str(label_file), size=(512, 512))
            output_path = images_dir / f"{image_id}.png"
            img.save(output_path, 'PNG')
            print(f"[OK] Created: {output_path}")
    
    print()
    print(f"Successfully created {len(label_files) if label_files else 3} sample images!")
    print(f"Images saved to: {images_dir}")


if __name__ == "__main__":
    create_all_sample_images()

149 lines•5.3 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer