在Google Earth Engine中过滤Landsat影像时出现黑色TIF图像

0 投票
1 回答
38 浏览
提问于 2025-04-14 18:29

我用以下的Python代码生成了一些黑色的TIF图像:

  • 中心点(center_point)
  • 宽度(width_meters)
  • 高度(height_meters)
  • 离地高度(height_from_ground)
  • 缩放比例(scale)
import ee
import requests
from datetime import datetime
import zipfile
import io

ee.Authenticate() 

# Initialize Google Earth Engine
ee.Initialize()

def generate_rectangle(center_point, width_meters, height_meters, height_from_ground):
    """
    Generate a rectangle based on center point, width, height, and height from ground.
    """
    center_lon, center_lat = center_point
    half_width = width_meters / 2
    half_height = height_meters / 2

    # Convert the width and height from meters to degrees
    degrees_per_meter = 1 / 111000  # Approximate conversion
    half_width_deg = half_width * degrees_per_meter
    half_height_deg = half_height * degrees_per_meter

    # Create rectangle vertices
    top_left = (center_lon - half_width_deg, center_lat + half_height_deg)
    top_right = (center_lon + half_width_deg, center_lat + half_height_deg)
    bottom_left = (center_lon - half_width_deg, center_lat - half_height_deg)
    bottom_right = (center_lon + half_width_deg, center_lat - half_height_deg)

    # Create rectangle geometry
    rectangle = ee.Geometry.Polygon([top_left, top_right, bottom_right, bottom_left])

    # Buffer the rectangle by height_from_ground
    buffered_rectangle = rectangle.buffer(height_from_ground)

    return buffered_rectangle

def collect_data(center_point, width_meters, height_meters, height_from_ground, output_folder, num_images):
    """
    Collect satellite images and GPS locations within a specified rectangle.
    """
    # Generate rectangle geometry
    rectangle = generate_rectangle(center_point, width_meters, height_meters, height_from_ground)

    # Filter satellite imagery
    dataset = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR') \
        .filterBounds(rectangle) \
        .filterDate('2015-01-01', '2020-12-31') \
        .sort('CLOUD_COVER') \
        .limit(num_images)

    # Iterate over images
    for i, image in enumerate(dataset.getInfo()['features']):
        # Get image ID
        image_id = image['id']
        print(f'Downloading image {i + 1}/{num_images}: {image_id}')

        # Get image metadata
        image_metadata = ee.Image(image_id).getInfo()

        # Get GPS coordinates
        coordinates = image_metadata['properties']['system:footprint']['coordinates']
        gps_coords = [(coord[1], coord[0]) for coord in coordinates]  # Fix here

        # Download image
        image_url = ee.Image(image_id).getDownloadURL({
            'scale': 250,  # Adjust scale as needed
            'crs': 'EPSG:4326',  # WGS84 coordinate system
            'region': gps_coords
        })

        # Save image
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        # Construct file name with timestamp
        filename = f"{timestamp}.zip"
        response = requests.get(image_url)

        if (response.status_code == 200):
            zip_file_bytes = io.BytesIO(response.content)
    
            # Create a ZipFile object from the file-like object
            with zipfile.ZipFile(zip_file_bytes, 'r') as zip_ref:
                # Extract all the contents to the specified folder
                zip_ref.extractall(timestamp + '\\')

                print("File downloaded successfully.")
        else:
            print("Failed to download file. Status code:", response.status_code)

# Example usage
center_point = (-122.084, 37.422)  # San Francisco coordinates
width_meters = 1000
height_meters = 1000
height_from_ground = 1000
output_folder = './/'
num_images = 1

# Collect data
collect_data(center_point, width_meters, height_meters, height_from_ground, output_folder, num_images)

收到的文件是一个压缩包,里面有好几张黑色的TIF图像。我本来希望能得到合适的GPS图像。如果有人能帮忙,我会非常感激。

1 个回答

1

问题出在 collect_data 函数的下一行:

gps_coords = [(coord[1], coord[0]) for coord in coordinates]  # Fix here

你应该先写经度,然后再写纬度,这样才能避免 GEE(谷歌地球引擎)生成一个和 ee.Geometry.Polygon 一样的多边形。具体可以参考这个文档

ee.Geometry.Polygon(aLng, aLat, bLng, bLat, ..., aLng, aLat)

如果经纬度顺序搞错了,导出的区域虽然看起来符合要求,但下载的图像却会出现问题,导致图像的波段不正确。

gps_coords = [(coord[0], coord[1]) for coord in coordinates]  # Fix here

收到的文件是一个压缩包,里面有好几个黑色的 tif 图像,我本来是想得到合适的 GPS 图像。

这些错误发生是因为用 (纬度, 经度) 而不是 (经度, 纬度) 创建的多边形,结果它出现在南极,那地方离我想要的 Landsat 图像远得很。

这是用修改后的代码下载的 B6 图像的一个例子。

希望这个回答对你有帮助。

撰写回答