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
ml_features.pyadvanced_visualization.pyadvanced_example.py
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
advanced_visualization.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Satellite Image Dataset - Advanced Visualization
Created by: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277

Advanced visualization features including:
- Interactive plots
- 3D visualizations
- Statistical analysis plots
- Comparison views
- Time series visualization
"""

import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import json
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
from matplotlib.patches import Rectangle, Polygon
from matplotlib.collections import PatchCollection


class AdvancedVisualizer:
    """
    Advanced visualization tools for satellite images.
    Created by: RSK World (https://rskworld.in)
    """
    
    def __init__(self, style: str = 'seaborn-v0_8'):
        """
        Initialize the visualizer.
        
        Args:
            style: Matplotlib style
        """
        plt.style.use(style)
        sns.set_palette("husl")
    
    def create_comparison_view(self, images: List[np.ndarray],
                              titles: Optional[List[str]] = None,
                              save_path: Optional[str] = None) -> None:
        """
        Create side-by-side comparison of multiple images.
        
        Args:
            images: List of images to compare
            titles: Optional list of titles
            save_path: Optional path to save figure
        """
        n_images = len(images)
        fig, axes = plt.subplots(1, n_images, figsize=(5*n_images, 5))
        
        if n_images == 1:
            axes = [axes]
        
        for i, (img, ax) in enumerate(zip(images, axes)):
            ax.imshow(img)
            ax.axis('off')
            if titles and i < len(titles):
                ax.set_title(titles[i], fontsize=12, fontweight='bold')
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            print(f"Saved comparison view to {save_path}")
        else:
            plt.show()
        
        plt.close()
    
    def visualize_statistics(self, image: np.ndarray,
                           save_path: Optional[str] = None) -> None:
        """
        Create comprehensive statistical visualization.
        
        Args:
            image: Input image
            save_path: Optional path to save figure
        """
        fig = plt.figure(figsize=(16, 10))
        
        # Original image
        ax1 = plt.subplot(2, 3, 1)
        ax1.imshow(image)
        ax1.set_title('Original Image', fontsize=12, fontweight='bold')
        ax1.axis('off')
        
        # Histogram
        ax2 = plt.subplot(2, 3, 2)
        if len(image.shape) == 3:
            colors = ['red', 'green', 'blue']
            for i, color in enumerate(colors):
                hist = np.histogram(image[:, :, i], bins=256, range=(0, 256))[0]
                ax2.plot(hist, color=color, alpha=0.7, label=color.capitalize())
            ax2.legend()
        else:
            hist = np.histogram(image, bins=256, range=(0, 256))[0]
            ax2.plot(hist, color='black')
        ax2.set_title('Histogram', fontsize=12, fontweight='bold')
        ax2.set_xlabel('Pixel Value')
        ax2.set_ylabel('Frequency')
        ax2.grid(True, alpha=0.3)
        
        # Statistics text
        ax3 = plt.subplot(2, 3, 3)
        ax3.axis('off')
        stats_text = f"""
        Image Statistics:
        
        Shape: {image.shape}
        Dtype: {image.dtype}
        Min: {np.min(image)}
        Max: {np.max(image)}
        Mean: {np.mean(image):.2f}
        Std: {np.std(image):.2f}
        Median: {np.median(image):.2f}
        """
        if len(image.shape) == 3:
            for i, color in enumerate(['Red', 'Green', 'Blue']):
                stats_text += f"\n{color} Channel:\n"
                stats_text += f"  Mean: {np.mean(image[:, :, i]):.2f}\n"
                stats_text += f"  Std: {np.std(image[:, :, i]):.2f}\n"
        
        ax3.text(0.1, 0.5, stats_text, fontsize=10, 
                verticalalignment='center', family='monospace')
        
        # Distribution plot
        ax4 = plt.subplot(2, 3, 4)
        if len(image.shape) == 3:
            for i, color in enumerate(['red', 'green', 'blue']):
                data = image[:, :, i].flatten()
                ax4.hist(data, bins=50, alpha=0.5, label=color.capitalize(), color=color)
            ax4.legend()
        else:
            ax4.hist(image.flatten(), bins=50, color='black', alpha=0.7)
        ax4.set_title('Pixel Value Distribution', fontsize=12, fontweight='bold')
        ax4.set_xlabel('Pixel Value')
        ax4.set_ylabel('Frequency')
        ax4.grid(True, alpha=0.3)
        
        # Box plot
        ax5 = plt.subplot(2, 3, 5)
        if len(image.shape) == 3:
            data = [image[:, :, i].flatten() for i in range(3)]
            labels = ['Red', 'Green', 'Blue']
            bp = ax5.boxplot(data, labels=labels, patch_artist=True)
            for patch, color in zip(bp['boxes'], ['red', 'green', 'blue']):
                patch.set_facecolor(color)
                patch.set_alpha(0.7)
        else:
            ax5.boxplot([image.flatten()], labels=['Grayscale'])
        ax5.set_title('Box Plot', fontsize=12, fontweight='bold')
        ax5.set_ylabel('Pixel Value')
        ax5.grid(True, alpha=0.3)
        
        # Heatmap (sample region)
        ax6 = plt.subplot(2, 3, 6)
        sample_size = min(100, image.shape[0], image.shape[1])
        if len(image.shape) == 3:
            sample = np.mean(image[:sample_size, :sample_size], axis=2)
        else:
            sample = image[:sample_size, :sample_size]
        im = ax6.imshow(sample, cmap='viridis', aspect='auto')
        ax6.set_title('Sample Heatmap', fontsize=12, fontweight='bold')
        plt.colorbar(im, ax=ax6)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            print(f"Saved statistics visualization to {save_path}")
        else:
            plt.show()
        
        plt.close()
    
    def visualize_3d_surface(self, image: np.ndarray,
                           sample_size: int = 100,
                           save_path: Optional[str] = None) -> None:
        """
        Create 3D surface plot of image.
        
        Args:
            image: Input image
            sample_size: Size of sample region for 3D plot
            save_path: Optional path to save figure
        """
        if len(image.shape) == 3:
            gray = np.mean(image, axis=2)
        else:
            gray = image
        
        # Sample region
        h, w = gray.shape
        sample_h = min(sample_size, h)
        sample_w = min(sample_size, w)
        sample = gray[:sample_h, :sample_w]
        
        # Create meshgrid
        x = np.arange(sample_w)
        y = np.arange(sample_h)
        X, Y = np.meshgrid(x, y)
        
        # Create 3D plot
        fig = plt.figure(figsize=(12, 10))
        ax = fig.add_subplot(111, projection='3d')
        
        surf = ax.plot_surface(X, Y, sample, cmap='terrain', 
                              linewidth=0, antialiased=True, alpha=0.8)
        
        ax.set_xlabel('X (pixels)')
        ax.set_ylabel('Y (pixels)')
        ax.set_zlabel('Pixel Value')
        ax.set_title('3D Surface Plot', fontsize=14, fontweight='bold')
        
        plt.colorbar(surf, ax=ax, shrink=0.5)
        
        if save_path:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            print(f"Saved 3D visualization to {save_path}")
        else:
            plt.show()
        
        plt.close()
    
    def visualize_time_series(self, images: List[np.ndarray],
                            dates: Optional[List[str]] = None,
                            save_path: Optional[str] = None) -> None:
        """
        Visualize time series of images.
        
        Args:
            images: List of images over time
            dates: Optional list of date strings
            save_path: Optional path to save figure
        """
        n_images = len(images)
        fig, axes = plt.subplots(1, n_images, figsize=(5*n_images, 5))
        
        if n_images == 1:
            axes = [axes]
        
        for i, (img, ax) in enumerate(zip(images, axes)):
            ax.imshow(img)
            ax.axis('off')
            if dates and i < len(dates):
                ax.set_title(dates[i], fontsize=10, fontweight='bold')
            else:
                ax.set_title(f'Time {i+1}', fontsize=10, fontweight='bold')
        
        plt.suptitle('Time Series Visualization', fontsize=14, fontweight='bold', y=1.02)
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            print(f"Saved time series to {save_path}")
        else:
            plt.show()
        
        plt.close()
    
    def visualize_with_overlays(self, image: np.ndarray,
                               buildings: Optional[List[Dict]] = None,
                               regions: Optional[List[Dict]] = None,
                               save_path: Optional[str] = None) -> None:
        """
        Visualize image with building and region overlays.
        
        Args:
            image: Base image
            buildings: Optional list of building detections
            regions: Optional list of land cover regions
            save_path: Optional path to save figure
        """
        fig, ax = plt.subplots(1, 1, figsize=(12, 12))
        ax.imshow(image)
        
        # Draw buildings
        if buildings:
            for building in buildings:
                if 'bbox' in building:
                    x, y, w, h = building['bbox']
                    rect = Rectangle((x, y), w, h, linewidth=2, 
                                   edgecolor='red', facecolor='none', alpha=0.8)
                    ax.add_patch(rect)
                    
                    # Add confidence label
                    conf = building.get('confidence', 0)
                    ax.text(x, y - 5, f'{conf:.2f}', color='red', 
                           fontsize=8, fontweight='bold',
                           bbox=dict(boxstyle='round', facecolor='white', alpha=0.7))
        
        # Draw regions
        if regions:
            colors = plt.cm.Set3(np.linspace(0, 1, len(regions)))
            for region, color in zip(regions, colors):
                if 'polygon' in region:
                    polygon = np.array(region['polygon'])
                    poly = Polygon(polygon, closed=True, 
                                 edgecolor=color, facecolor=color, 
                                 alpha=0.3, linewidth=2)
                    ax.add_patch(poly)
                    
                    # Add label
                    if 'class' in region:
                        center = polygon.mean(axis=0)
                        ax.text(center[0], center[1], region['class'],
                               fontsize=10, fontweight='bold',
                               bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
        
        ax.set_title('Satellite Image with Overlays', fontsize=14, fontweight='bold')
        ax.axis('off')
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            print(f"Saved overlay visualization to {save_path}")
        else:
            plt.show()
        
        plt.close()
    
    def create_dashboard(self, image: np.ndarray,
                        features: Optional[Dict] = None,
                        metadata: Optional[Dict] = None,
                        save_path: Optional[str] = None) -> None:
        """
        Create comprehensive dashboard visualization.
        
        Args:
            image: Main image
            features: Optional extracted features
            metadata: Optional metadata
            save_path: Optional path to save figure
        """
        fig = plt.figure(figsize=(20, 12))
        
        # Main image
        ax1 = plt.subplot(2, 3, (1, 2))
        ax1.imshow(image)
        ax1.set_title('Satellite Image', fontsize=14, fontweight='bold')
        ax1.axis('off')
        
        # Histogram
        ax2 = plt.subplot(2, 3, 3)
        if len(image.shape) == 3:
            for i, color in enumerate(['red', 'green', 'blue']):
                hist = np.histogram(image[:, :, i], bins=50)[0]
                ax2.plot(hist, color=color, alpha=0.7, label=color.capitalize())
            ax2.legend()
        else:
            hist = np.histogram(image, bins=50)[0]
            ax2.plot(hist, color='black')
        ax2.set_title('Histogram', fontsize=12, fontweight='bold')
        ax2.grid(True, alpha=0.3)
        
        # Features (if provided)
        if features:
            ax3 = plt.subplot(2, 3, 4)
            ax3.axis('off')
            features_text = "Extracted Features:\n\n"
            for key, value in list(features.items())[:10]:
                if isinstance(value, (int, float)):
                    features_text += f"{key}: {value:.4f}\n"
                elif isinstance(value, list) and len(value) < 20:
                    features_text += f"{key}: {value}\n"
            ax3.text(0.1, 0.5, features_text, fontsize=9, 
                    verticalalignment='center', family='monospace')
        
        # Metadata (if provided)
        if metadata:
            ax4 = plt.subplot(2, 3, 5)
            ax4.axis('off')
            metadata_text = "Metadata:\n\n"
            for key, value in list(metadata.items())[:10]:
                metadata_text += f"{key}: {value}\n"
            ax4.text(0.1, 0.5, metadata_text, fontsize=9,
                    verticalalignment='center', family='monospace')
        
        # Statistics
        ax5 = plt.subplot(2, 3, 6)
        stats = {
            'Mean': np.mean(image),
            'Std': np.std(image),
            'Min': np.min(image),
            'Max': np.max(image)
        }
        ax5.bar(stats.keys(), stats.values(), color=['blue', 'green', 'orange', 'red'], alpha=0.7)
        ax5.set_title('Statistics', fontsize=12, fontweight='bold')
        ax5.set_ylabel('Value')
        ax5.grid(True, alpha=0.3, axis='y')
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=150, bbox_inches='tight')
            print(f"Saved dashboard to {save_path}")
        else:
            plt.show()
        
        plt.close()


def main():
    """
    Example usage of AdvancedVisualizer.
    Created by: RSK World (https://rskworld.in)
    """
    print("Advanced Visualization - Example")
    print("Created by: RSK World (https://rskworld.in)")
    print("-" * 50)
    
    visualizer = AdvancedVisualizer()
    
    # Create sample image
    sample_image = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8)
    
    # Statistics visualization
    visualizer.visualize_statistics(sample_image, save_path="visualizations/stats_example.png")
    
    # 3D surface
    visualizer.visualize_3d_surface(sample_image, save_path="visualizations/3d_example.png")
    
    print("\nAdvanced visualization complete!")


if __name__ == "__main__":
    main()
436 lines•15.5 KB
python
advanced_example.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Satellite Image Dataset - Advanced Features Example
Created by: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277

This script demonstrates all advanced features:
- Advanced image processing
- Machine learning integration
- Real image downloading
- Advanced visualization
- Batch processing
"""

import numpy as np
from pathlib import Path
import cv2
import json

# Import advanced modules
try:
    from advanced_processing import AdvancedImageProcessor
    from ml_integration import SatelliteMLProcessor
    from enhanced_real_image_downloader import EnhancedRealImageDownloader
    from advanced_visualization import AdvancedVisualizer
    from batch_processing import BatchProcessor, ImageAugmenter
    from data_loader import SatelliteDatasetLoader
except ImportError as e:
    print(f"Import error: {e}")
    print("Make sure all modules are in the same directory.")
    exit(1)


def demonstrate_advanced_processing():
    """Demonstrate advanced image processing features."""
    print("\n" + "=" * 60)
    print("1. ADVANCED IMAGE PROCESSING")
    print("=" * 60)
    
    processor = AdvancedImageProcessor()
    
    # Create sample image
    sample_image = np.random.randint(0, 255, (512, 512, 3), dtype=np.uint8)
    print(f"Sample image shape: {sample_image.shape}")
    
    # Edge detection
    print("\n1.1 Edge Detection")
    edges = processor.detect_edges(sample_image, method='canny')
    print(f"   Edges detected: {edges.shape}")
    
    # Segmentation
    print("\n1.2 Image Segmentation")
    segmented, props = processor.segment_image(sample_image, method='slic', num_segments=10)
    print(f"   Segmented into {props['num_segments']} regions")
    
    # Feature extraction
    print("\n1.3 Feature Extraction")
    features = processor.extract_all_features(sample_image)
    print(f"   Extracted {len(features)} feature types:")
    for key in features.keys():
        print(f"     - {key}")
    
    # Image enhancement
    print("\n1.4 Image Enhancement")
    enhanced = processor.enhance_image(sample_image, method='clahe')
    print(f"   Enhanced image shape: {enhanced.shape}")
    
    # Noise reduction
    print("\n1.5 Noise Reduction")
    denoised = processor.reduce_noise(sample_image, method='bilateral')
    print(f"   Denoised image shape: {denoised.shape}")


def demonstrate_ml_integration():
    """Demonstrate ML integration features."""
    print("\n" + "=" * 60)
    print("2. MACHINE LEARNING INTEGRATION")
    print("=" * 60)
    
    ml_processor = SatelliteMLProcessor()
    
    # Create sample data
    sample_image = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8)
    sample_label = np.random.randint(0, 5, (256, 256), dtype=np.uint8)
    
    # Feature extraction for ML
    print("\n2.1 Feature Extraction for ML")
    features, positions = ml_processor.extract_features_for_ml(sample_image)
    print(f"   Extracted {len(features)} feature vectors")
    print(f"   Feature vector shape: {features.shape}")
    
    # Building detection
    print("\n2.2 Building Detection")
    buildings = ml_processor.detect_buildings_simple(sample_image)
    print(f"   Detected {len(buildings)} buildings")
    if buildings:
        print(f"   Example building: {buildings[0]}")
    
    # NDVI extraction
    print("\n2.3 NDVI Extraction")
    ndvi = ml_processor.extract_ndvi(sample_image)
    print(f"   NDVI map shape: {ndvi.shape}")
    print(f"   NDVI range: [{ndvi.min()}, {ndvi.max()}]")
    
    # Change detection
    print("\n2.4 Change Detection")
    image2 = sample_image.copy()
    image2[100:150, 100:150] = 255  # Simulate change
    change_map, stats = ml_processor.detect_changes(sample_image, image2)
    print(f"   Change percentage: {stats['change_percentage']:.2f}%")
    print(f"   Mean difference: {stats['mean_difference']:.4f}")


def demonstrate_real_image_download():
    """Demonstrate real image downloading."""
    print("\n" + "=" * 60)
    print("3. REAL IMAGE DOWNLOADING")
    print("=" * 60)
    
    downloader = EnhancedRealImageDownloader()
    
    print("\n3.1 Planetary Computer Download (No credentials needed)")
    print("   Note: This requires internet connection and packages:")
    print("   pip install pystac-client planetary-computer requests pillow")
    
    try:
        # Try to download (will fail if packages not installed, but shows how it works)
        files = downloader.download_sample_real_images(num_images=2)
        if files:
            print(f"   Successfully downloaded {len(files)} images!")
        else:
            print("   Download skipped (packages may not be installed)")
    except Exception as e:
        print(f"   Download test skipped: {e}")
    
    print("\n3.2 Other Sources Available:")
    print("   - USGS EarthExplorer (Landsat)")
    print("   - Copernicus Hub (Sentinel-2)")
    print("   See enhanced_real_image_downloader.py for details")


def demonstrate_advanced_visualization():
    """Demonstrate advanced visualization features."""
    print("\n" + "=" * 60)
    print("4. ADVANCED VISUALIZATION")
    print("=" * 60)
    
    visualizer = AdvancedVisualizer()
    
    # Create sample data
    sample_image = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8)
    
    # Ensure visualizations directory exists
    viz_dir = Path("visualizations")
    viz_dir.mkdir(exist_ok=True)
    
    print("\n4.1 Statistical Visualization")
    visualizer.visualize_statistics(sample_image, 
                                    save_path=str(viz_dir / "stats_example.png"))
    print("   Saved statistics visualization")
    
    print("\n4.2 3D Surface Plot")
    visualizer.visualize_3d_surface(sample_image,
                                    save_path=str(viz_dir / "3d_example.png"))
    print("   Saved 3D visualization")
    
    print("\n4.3 Comparison View")
    image2 = cv2.flip(sample_image, 1)
    visualizer.create_comparison_view([sample_image, image2],
                                     titles=['Original', 'Flipped'],
                                     save_path=str(viz_dir / "comparison_example.png"))
    print("   Saved comparison view")
    
    print("\n4.4 Dashboard")
    features = {'mean': np.mean(sample_image), 'std': np.std(sample_image)}
    metadata = {'source': 'sample', 'size': '256x256'}
    visualizer.create_dashboard(sample_image, features, metadata,
                                save_path=str(viz_dir / "dashboard_example.png"))
    print("   Saved dashboard")


def demonstrate_batch_processing():
    """Demonstrate batch processing and augmentation."""
    print("\n" + "=" * 60)
    print("5. BATCH PROCESSING & AUGMENTATION")
    print("=" * 60)
    
    augmenter = ImageAugmenter()
    
    # Create sample image
    sample_image = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8)
    
    print("\n5.1 Image Augmentation")
    augmented = augmenter.augment_image(sample_image, 
                                       ['flip_horizontal', 'brightness', 'rotate'])
    print(f"   Created {len(augmented)} augmented versions")
    
    print("\n5.2 Available Augmentations:")
    aug_methods = ['flip_horizontal', 'flip_vertical', 'rotate', 
                  'brightness', 'contrast', 'noise', 'crop', 'scale']
    for method in aug_methods:
        print(f"   - {method}")
    
    print("\n5.3 Batch Processing")
    print("   Use BatchProcessor for parallel processing of multiple images")
    print("   Supports ThreadPoolExecutor for efficient processing")


def demonstrate_integration():
    """Demonstrate integration of all features."""
    print("\n" + "=" * 60)
    print("6. INTEGRATED WORKFLOW EXAMPLE")
    print("=" * 60)
    
    # Load dataset
    loader = SatelliteDatasetLoader()
    info = loader.get_dataset_info()
    
    print(f"\n6.1 Dataset Information:")
    print(f"   Total images: {info['total_images']}")
    print(f"   Has labels: {info['has_labels']}")
    print(f"   Has buildings: {info['has_buildings']}")
    print(f"   Has metadata: {info['has_metadata']}")
    
    if info['total_images'] > 0:
        image_id = "sample_001"
        print(f"\n6.2 Processing {image_id}:")
        
        # Load image
        image, labels = loader.load_image_pair(image_id)
        if image is not None:
            print(f"   Loaded image: {image.shape}")
            
            # Advanced processing
            adv_processor = AdvancedImageProcessor()
            features = adv_processor.extract_all_features(image)
            print(f"   Extracted advanced features: {len(features)} types")
            
            # ML processing
            ml_processor = SatelliteMLProcessor()
            buildings = ml_processor.detect_buildings_simple(image)
            print(f"   Detected {len(buildings)} buildings")
            
            # Visualization
            if labels:
                visualizer = AdvancedVisualizer()
                viz_dir = Path("visualizations")
                viz_dir.mkdir(exist_ok=True)
                visualizer.visualize_statistics(image,
                                               save_path=str(viz_dir / f"{image_id}_stats.png"))
                print(f"   Created visualization")
        else:
            print(f"   Image not found, using sample data")
    else:
        print("\n   No images in dataset. Add images to data/images/ to see full workflow.")


def main():
    """Main function demonstrating all advanced features."""
    print("=" * 60)
    print("SATELLITE IMAGE DATASET - ADVANCED FEATURES DEMO")
    print("Created by: RSK World (https://rskworld.in)")
    print("=" * 60)
    
    try:
        # 1. Advanced Processing
        demonstrate_advanced_processing()
        
        # 2. ML Integration
        demonstrate_ml_integration()
        
        # 3. Real Image Download
        demonstrate_real_image_download()
        
        # 4. Advanced Visualization
        demonstrate_advanced_visualization()
        
        # 5. Batch Processing
        demonstrate_batch_processing()
        
        # 6. Integration
        demonstrate_integration()
        
        print("\n" + "=" * 60)
        print("ADVANCED FEATURES DEMONSTRATION COMPLETE!")
        print("=" * 60)
        print("\nAll advanced features are now available:")
        print("  ✓ Advanced image processing (edge detection, segmentation, features)")
        print("  ✓ Machine learning integration (classification, detection)")
        print("  ✓ Real image downloading (multiple sources)")
        print("  ✓ Advanced visualization (3D, statistics, dashboards)")
        print("  ✓ Batch processing and augmentation")
        print("\nFor more information, visit: https://rskworld.in")
        print("=" * 60)
    
    except Exception as e:
        print(f"\nError during demonstration: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

307 lines•11 KB
python

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