Home - Black-Lights/planetscope-py GitHub Wiki

PlanetScope-py

Professional Python library for PlanetScope satellite imagery analysis with enhanced interactive workflows

Python 3.10+ Library Complete Test Coverage License: MIT

Project Overview

PlanetScope-py is a comprehensive Python library designed for remote sensing researchers, GIS analysts, and Earth observation professionals who need reliable tools for working with PlanetScope satellite imagery. The library provides a complete foundation for satellite imagery workflows, from interactive ROI selection to advanced spatial-temporal density analysis, asset management, and professional data export.

Current Status

Library Status: Complete with Interactive Workflows
Version: 4.1.0 (Enhanced Metadata Processing & Interactive Features)
Test Coverage: 349 tests passing Real Planet API: Fully integrated and tested
Interactive Features: Complete ROI selection and satellite preview system
Spatial Analysis: Three computational methods implemented
Temporal Analysis: Complete grid-based temporal pattern analysis with enhanced turbo colormap visualizations
Asset Management: Quota monitoring and download management
Data Export: Professional GeoPackage creation with imagery support
Metadata Processing: Enhanced scene ID extraction from all Planet API endpoints
ROI Input Support: Interactive drawing, shapefiles, GeoJSON, WKT, and coordinate lists
Python Support: 3.10+
License: MIT

Key Features

Interactive ROI Selection & Preview System (FEATURED)

The crown jewel of PlanetScope-py is its interactive workflow system that makes satellite imagery analysis accessible to everyone:

Interactive ROI Manager

  • Visual ROI Selection: Draw polygons directly on interactive maps - no need to manually code coordinates
  • Preset Locations: Quick access to common study areas (Milan, London, San Francisco, Tokyo, etc.)
  • Multiple Export Formats: Save ROI as GeoJSON, Shapefile, WKT, or Python objects
  • Shapely Integration: Seamless conversion between interactive maps and analysis workflows
  • Jupyter Optimized: Perfect integration with Jupyter notebooks for research workflows

Satellite Preview Manager

  • Actual Imagery Preview: See real Planet satellite scenes overlaid on your ROI before analysis
  • Quality Filtering: Apply cloud cover and quality filters to preview only the best scenes
  • Interactive Maps: Browse through available satellite scenes with detailed metadata popups
  • Scene Information: View acquisition dates, cloud cover, sun elevation, and quality metrics
  • Export Capabilities: Save preview maps as standalone HTML files for presentations

Complete Interactive Workflow

# Step 1: Interactive ROI Selection
from planetscope_py import jupyter_roi_selector
roi_map = jupyter_roi_selector("milan")
roi_map  # Draw your ROI and export as 'roi_selection.geojson'

# Step 2: Preview Actual Satellite Imagery
from planetscope_py import create_scene_preview_map
preview_map = create_scene_preview_map(
    "roi_selection.geojson",  # Your drawn ROI
    "2025-01-01/2025-01-31",
    max_scenes=20,
    cloud_cover_max=0.1  # Show only high-quality scenes
)
preview_map  # Interactive map with real satellite imagery!

# Step 3: Run Analysis
from planetscope_py import jupyter_quick_analysis
result = jupyter_quick_analysis(
    "roi_selection.geojson", "2025-01-01/2025-01-31", "both"
)
print(f"Spatial: {result['spatial_analysis']['scenes_found']} scenes")
print(f"Temporal: {result['temporal_analysis']['scenes_found']} scenes")

Enhanced Metadata Processing (NEW in v4.1.0)

  • Multi-Source Scene ID Extraction: Robust scene ID detection from all Planet API endpoints (Search, Stats, Orders)
  • Planet API Compatibility: Works reliably across different API response formats
  • Fallback ID Detection: Comprehensive checking of properties.id, top-level id, item_id, and scene_id fields
  • Complete JSON Export: Fixed truncated metadata files with proper numpy type serialization
  • Error Recovery: Graceful handling of missing or malformed scene identifiers

JSON Serialization Fixes (NEW in v4.1.0)

  • Complete Metadata Export: No more truncated analysis_metadata.json files
  • Numpy Type Conversion: Proper handling of numpy.int64, numpy.float64, numpy.ndarray, and numpy.nan values
  • Memory Efficiency: Optimized serialization of large data structures
  • Nested Object Support: Recursive conversion of complex metadata dictionaries and lists

Enhanced Temporal Analysis Visualizations (NEW in v4.1.0)

  • Turbo Colormap: Improved temporal analysis visualizations with better color contrast and data interpretation
  • Consistent Summary Tables: Temporal analysis tables now match spatial density format
  • Professional Presentation: Enhanced visual consistency across all analysis types
  • Better Data Understanding: Improved visibility and accessibility in temporal plots

Scene Discovery System

  • Advanced Search: Spatiotemporal filtering with cloud cover, sun elevation, and quality thresholds
  • Multi-geometry Support: Points, polygons, and complex geometries with automatic validation
  • Flexible ROI Input: Support for shapefiles (.shp), GeoJSON files (.geojson), WKT strings, and coordinate lists
  • Batch Operations: Process multiple regions simultaneously with intelligent rate limiting
  • Smart Filtering: Quality-based scene selection with comprehensive metadata analysis

Spatial Analysis Engine

  • Multi-Algorithm Density Calculation: Three computational methods for different use cases
  • High-Resolution Analysis: Support for 3m to 1000m grid resolutions
  • Performance Optimization: Automatic method selection based on dataset characteristics
  • Memory Efficient Processing: Adaptive grid and chunking for large areas
  • Professional Visualization: GeoTIFF export with QGIS styling

Temporal Analysis Engine

  • Grid-Based Temporal Pattern Analysis: Complete temporal analysis using coordinate-corrected grid approach
  • Multiple Temporal Metrics: Coverage days, mean/median intervals, temporal density, and coverage frequency
  • Performance Optimization: FAST and ACCURATE methods with automatic selection based on grid size
  • Professional Outputs: GeoTIFF files with QML styling, comprehensive summary plots, and JSON metadata
  • Enhanced Visualizations: Turbo colormap for better data interpretation
  • ROI Integration: Same flexible ROI input support as other modules

Asset Management System

  • Intelligent Quota Monitoring: Real-time tracking of Planet subscription usage across multiple APIs
  • Asset Activation & Download: Automated asset processing with progress tracking
  • Download Management: Parallel downloads with retry logic and error recovery
  • User Confirmation System: Interactive prompts for download decisions with impact calculation
  • ROI Clipping Support: Automatic scene clipping to regions of interest during download

Professional Data Export

  • GeoPackage Creation: Comprehensive GeoPackage files with enhanced scene metadata
  • Multi-Layer Support: Vector polygons and raster imagery in standardized format
  • GIS Software Integration: Direct compatibility with QGIS, ArcGIS, and other professional tools
  • Enhanced Attribute Schemas: Reliable scene IDs and metadata from all API sources
  • QGIS Styling: Automatic generation of .qml style files for immediate visualization

Robust Infrastructure

  • Authentication System: Hierarchical API key detection with secure credential management
  • Configuration Management: Multi-source configuration with environment variable support
  • Input Validation: Comprehensive geometry, date, and parameter validation with file path support
  • Exception Handling: Professional error hierarchy with detailed context and troubleshooting guidance
  • Cross-Platform: Full compatibility with Windows, macOS, and Linux environments

Interactive Workflow Architecture

Interactive PlanetScope-py Workflow
├── Interactive ROI Selection
│   ├── Visual Map Drawing (jupyter_roi_selector)
│   ├── Preset Location Maps (Milan, London, SF, etc.)
│   ├── Multi-Format Export (GeoJSON, Shapefile, WKT)
│   └── Shapely Integration (jupyter_get_shapely_roi)
├── Satellite Preview System
│   ├── Actual Imagery Preview (create_scene_preview_map)
│   ├── Quality Filtering & Scene Information
│   ├── Interactive Map Browsing
│   └── Export Capabilities
├── Enhanced Analysis Engine
│   ├── Spatial Density Analysis (with complete JSON export)
│   ├── Temporal Pattern Analysis (with turbo colormap)
│   ├── Enhanced Metadata Processing
│   └── Professional Visualization
├── Asset Management & Export
│   ├── Quota Monitoring & Downloads
│   ├── Enhanced GeoPackage Creation
│   └── Professional Data Export
└── Jupyter Integration
    ├── Complete Workflow Functions
    ├── One-Line Analysis Tools
    └── Interactive Demonstrations

Use Cases

Use Case 1: Interactive Research Workflow (FEATURED)

Perfect for: Researchers, students, and analysts new to satellite imagery

  • Visual ROI Selection: Draw study areas directly on interactive maps
  • Satellite Preview: See actual imagery before committing to analysis
  • Quality Assessment: Preview scene quality with cloud cover and metadata filters
  • Seamless Analysis: Move from interactive selection to professional analysis
  • Presentation Ready: Export interactive maps for reports and presentations

Use Case 2: Enhanced Scene Discovery & Quality Assessment

Perfect for: Data acquisition workflows, operational monitoring

  • Enhanced Metadata Processing: Reliable scene identification from all Planet API sources
  • Advanced Quality Filtering: Custom criteria with comprehensive metadata analysis
  • Complete Export: Full JSON metadata without truncation issues
  • Flexible Output Options: Multiple formats for downstream analysis workflows
  • ROI Support: Use existing shapefiles and GeoJSON files directly

Use Case 3: Advanced Spatial and Temporal Analysis

Perfect for: Research applications, monitoring programs, acquisition planning

  • Spatial Density Calculations: Multiple optimized algorithms with complete metadata export
  • Enhanced Temporal Analysis: Grid-based patterns with improved turbo colormap visualizations
  • Performance Optimization: FAST and ACCURATE methods with automatic selection
  • Professional Visualization: Consistent formatting and enhanced color schemes
  • Comprehensive Export: Complete metadata and visualization files

Use Case 4: Professional Asset Management & Export

Perfect for: Operational workflows, data acquisition management

  • Intelligent Quota Monitoring: Real-time usage tracking with enhanced reporting
  • Asset Management: Download workflows with ROI clipping
  • Enhanced GeoPackage Export: Reliable scene metadata from all API sources
  • Professional Integration: Seamless GIS software compatibility

Quick Start

Interactive Workflow (RECOMMENDED)

# Complete interactive workflow for beginners
from planetscope_py import (
    jupyter_roi_selector, create_scene_preview_map, 
    jupyter_quick_analysis, jupyter_get_shapely_roi
)

# Step 1: Interactive ROI Selection
print("Step 1: Draw your ROI on the interactive map")
roi_map = jupyter_roi_selector("milan")  # Creates interactive map
roi_map  # Draw polygon and export as 'roi_selection.geojson'

# Step 2: Preview Actual Satellite Imagery  
print("Step 2: Preview real satellite scenes over your ROI")
preview_map = create_scene_preview_map(
    "roi_selection.geojson",     # Your exported ROI
    "2025-01-01/2025-01-31",     # Time period
    max_scenes=20,               # Show up to 20 scenes
    cloud_cover_max=0.1          # Only high-quality scenes
)
preview_map  # Interactive map with real Planet imagery!

# Step 3: Complete Analysis
print("Step 3: Run comprehensive analysis")
result = jupyter_quick_analysis(
    "roi_selection.geojson",     # Same ROI file
    "2025-01-01/2025-01-31",     # Same time period
    "both"                       # Both spatial and temporal analysis
)

print(f"Analysis complete!")
print(f"Spatial analysis: {result['spatial_analysis']['scenes_found']} scenes")
print(f"Temporal analysis: {result['temporal_analysis']['scenes_found']} scenes")
print(f"Output directory: {result['spatial_analysis']['output_directory']}")

# Step 4: Work with Shapely Objects (Advanced)
roi_polygon = jupyter_get_shapely_roi("roi_selection.geojson")
print(f"ROI area: {roi_polygon.area:.6f} square degrees")

Enhanced Scene Search with Reliable Metadata (v4.1.0)

from planetscope_py import PlanetScopeQuery

# Initialize query system
query = PlanetScopeQuery()

# Search scenes with enhanced metadata processing
results = query.search_scenes(
    geometry=r'C:\path\to\study_area.shp',  # Direct file support
    start_date="2025-01-01",
    end_date="2025-01-31",
    cloud_cover_max=0.2,
    item_types=["PSScene"]
)

# v4.1.0: Enhanced metadata extraction now works reliably
for scene in results['features'][:3]:
    metadata = query.metadata_processor.extract_scene_metadata(scene)
    print(f"Scene ID: {metadata['scene_id']}")  # Now always works!
    print(f"Cloud cover: {metadata['cloud_cover']*100:.1f}%")
    print(f"Quality: {metadata['quality_category']}")

Advanced Interactive Preview with Quality Filtering

from planetscope_py import quick_preview_with_shapely, PlanetScopeQuery, jupyter_get_shapely_roi

# Load ROI from interactive selection
roi_polygon = jupyter_get_shapely_roi("roi_selection.geojson")

# Create query instance
query = PlanetScopeQuery()

# Advanced preview with quality filtering
preview_map = quick_preview_with_shapely(
    query_instance=query,
    roi_polygon=roi_polygon,
    time_period="2025-01-01/2025-01-31",
    max_scenes=25,
    cloud_cover_max=0.05,        # Very strict cloud filtering
    sun_elevation_min=40,        # Good lighting conditions
    quality_category="standard"  # Standard quality only
)

preview_map  # Shows only the highest quality scenes!

Enhanced Temporal Analysis with Turbo Colormap (v4.1.0)

from planetscope_py import analyze_roi_temporal_patterns

# Enhanced temporal analysis with improved visualizations
result = analyze_roi_temporal_patterns(
    "roi_selection.geojson",     # From interactive selection
    "2025-01-01/2025-03-31",     # 3-month period
    spatial_resolution=100,
    optimization_level="auto",    # Automatic FAST/ACCURATE selection
    clip_to_roi=True,
    create_visualizations=True   # Enhanced turbo colormap visualizations
)

print(f"Found {result['scenes_found']} scenes")
print(f"Mean coverage days: {result['temporal_result'].temporal_stats['mean_coverage_days']:.1f}")
print(f"Enhanced visualizations with turbo colormap created!")
print(f"Complete metadata exported: {result['exports']['metadata']}")

Complete Interactive to Professional Workflow

from planetscope_py import (
    jupyter_roi_selector, create_scene_preview_map, 
    analyze_roi_temporal_patterns, create_scene_geopackage
)

# Interactive workflow pipeline
def interactive_to_professional_workflow():
    """Complete workflow from interactive selection to professional export."""
    
    # Phase 1: Interactive ROI Selection
    print("Phase 1: Interactive ROI Selection")
    roi_map = jupyter_roi_selector("milan")
    return roi_map  # User draws ROI and exports
    
def preview_and_analyze(roi_file="roi_selection.geojson"):
    """Phase 2-4: Preview, analyze, and export."""
    
    # Phase 2: Preview Satellite Imagery
    print("Phase 2: Previewing satellite imagery...")
    preview_map = create_scene_preview_map(
        roi_file, "2025-01-01/2025-01-31", 
        max_scenes=20, cloud_cover_max=0.1
    )
    
    # Phase 3: Enhanced Temporal Analysis
    print("Phase 3: Running enhanced temporal analysis...")
    temporal_result = analyze_roi_temporal_patterns(
        roi_file, "2025-01-01/2025-03-31",
        create_visualizations=True,  # Turbo colormap visualizations
        export_geotiffs=True
    )
    
    # Phase 4: Professional Export
    print("Phase 4: Creating professional GeoPackage...")
    gpkg_path = create_scene_geopackage(
        roi_file, "2025-01-01/2025-01-31",
        schema="comprehensive"  # Enhanced metadata
    )
    
    return {
        'preview_map': preview_map,
        'temporal_analysis': temporal_result,
        'geopackage': gpkg_path,
        'interactive_to_professional': 'Complete!'
    }

# Run interactive workflow
print("Starting interactive workflow...")
roi_map = interactive_to_professional_workflow()
# After user draws ROI and exports:
# results = preview_and_analyze()

Installation

Standard Installation

pip install planetscope-py

Enhanced Installation (with interactive features)

pip install planetscope-py[jupyter]

Full Installation (all features)

pip install planetscope-py[all]

Development Installation

git clone https://github.com/Black-Lights/planetscope-py.git
cd planetscope-py
pip install -e .

Prerequisites for Interactive Features

  • Python 3.10 or higher
  • Planet API key (sign up at planet.com)
  • Jupyter Notebook or JupyterLab for interactive features
  • Internet connection for API access and map tiles
  • Optional: GeoPandas for enhanced shapefile support

What's New in v4.1.0

Enhanced Metadata Processing

  • Reliable Scene ID Extraction: Now works with all Planet API endpoints (Search, Stats, Orders)
  • Multi-Source Detection: Comprehensive fallback logic for scene identification
  • Complete JSON Export: Fixed truncated metadata files with proper numpy type conversion
  • Error Recovery: Graceful handling of missing or malformed scene data

Improved Visualizations

  • Turbo Colormap: Enhanced temporal analysis visualizations with better contrast
  • Consistent Formatting: Temporal summary tables match spatial density format
  • Professional Presentation: Standardized color schemes across all analysis types
  • Better Accessibility: Improved visibility and data interpretation

Interactive Manager Enhancements

  • Enhanced Integration: Improved preview and interactive manager configuration
  • Better Error Handling: Clear feedback about component status and dependencies
  • Success Reporting: Enhanced module loading confirmations
  • Seamless Workflows: Smoother integration between interactive and analysis components

Success Metrics

Metric Target Current Status
Test Coverage >90% 349 tests
Python Support 3.10+ Implemented
Cross-Platform Windows/macOS/Linux Validated
API Integration Full Planet API Complete with enhanced metadata
Interactive Features Complete workflow Implemented and optimized
Spatial Analysis Multi-algorithm Complete with enhanced export
Temporal Analysis Grid-based patterns Complete with turbo colormap
ROI Input Support Multiple formats Complete (.shp, .geojson, .wkt, interactive)
Asset Management Quota monitoring Complete
Data Export Professional GeoPackage Complete with enhanced metadata
Documentation Comprehensive Complete with interactive examples

Target Users

  • Researchers and Students looking for intuitive satellite imagery analysis tools
  • Remote sensing professionals needing interactive workflows for operational applications
  • GIS analysts requiring visual ROI selection and satellite preview capabilities
  • Earth observation professionals building specialized analysis tools with enhanced metadata
  • Environmental monitoring agencies requiring reliable satellite data analysis
  • Academic institutions engaged in remote sensing education with interactive components
  • Commercial organizations developing satellite imagery applications with professional export

Interactive Features Demo

Try our interactive features live:

  1. ROI Selection Demo: Interactive ROI Selection Guide
  2. Satellite Preview Demo: Satellite Preview Tutorial
  3. Complete Workflow Demo: End-to-End Interactive Workflow

Development Team

Authors: Ammar & Umayr
Project Advisor: Dr. Daniela Stroppiana
Supervisor: Prof. Giovanna Venuti
Institution: Politecnico di Milano - Geoinformatics Engineering Program

Contributing

We welcome contributions! Please see our Contributing Guide for details on:

  • Development setup and environment configuration
  • Interactive feature development guidelines
  • Code quality standards and linting requirements
  • Testing requirements and coverage expectations
  • Documentation guidelines and interactive examples
  • Pull request process and review criteria

License

This project is licensed under the MIT License. See the LICENSE file for details.

Acknowledgments

  • Planet Labs PBC for providing the Planet API and PlanetScope imagery
  • Open Source Community for the excellent geospatial Python ecosystem
  • Folium and Leaflet for enabling interactive mapping capabilities
  • Jupyter Project for the notebook environment that makes interactive analysis possible
  • Politecnico di Milano for academic support and guidance

Support


Note: This project is independently developed and is not officially affiliated with Planet Labs PBC. It is designed to work with Planet's publicly available APIs following their terms of service.