You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python调用GDAL实现影像重采样并保存为PNG格式?

Replicate gdal_translate Resampling & PNG Export in Python GDAL

Hey there! Let's break down how to mirror that gdal_translate command you're using into working Python GDAL code. First, let's recap what your command line does:

gdal_translate -of PNG -outsize 10% 10% image.bsq image.png
This tells GDAL to take your BSQ input image, resize it to 10% of its original dimensions (resampling in the process), and save the result as a PNG.

Your current Python code is close, but it has two key issues: you're targeting GTiff instead of PNG, and there's no logic for resizing/resampling. The easiest way to match your command line behavior is to use gdal.Translate()—this is the official Python binding for the gdal_translate utility, so it maps directly to the command line options you already know.

Full Working Code (Direct gdal_translate Equivalent)

from osgeo import gdal

# Set your input/output paths
input_bsq = "image.bsq"
output_png = "image.png"

# Define options that match your command line arguments
translate_opts = gdal.TranslateOptions(
    format="PNG",  # Matches `-of PNG`
    outsize=("10%", "10%"),  # Matches `-outsize 10% 10%`
    # Optional: Add a resampling algorithm if you don't want the default nearest neighbor
    # resampleAlg="bilinear"  # Uncomment this for smoother resizing
)

# Run the translation (handles resampling + format conversion)
gdal.Translate(output_png, input_bsq, options=translate_opts)

# Cleanup (GDAL handles this automatically in most cases, but good practice)
del translate_opts

Alternative: Manual Approach (For More Control)

If you want to build the dataset step-by-step instead of using the Translate wrapper, here's how to do it. This fixes the issues in your original code and adds resampling logic:

from osgeo import gdal

input_bsq = "image.bsq"
output_png = "image.png"

# Open the source BSQ image
src_ds = gdal.Open(input_bsq)
if not src_ds:
    raise ValueError(f"Failed to open input file: {input_bsq}")

# Calculate new dimensions (10% of original size)
orig_width, orig_height = src_ds.RasterXSize, src_ds.RasterYSize
new_width = int(orig_width * 0.1)
new_height = int(orig_height * 0.1)

# Get the PNG driver (make sure GDAL has it enabled)
png_driver = gdal.GetDriverByName("PNG")
if not png_driver:
    raise RuntimeError("PNG driver is not available in your GDAL installation")

# Create the empty PNG output dataset with the new dimensions
dst_ds = png_driver.Create(
    output_png,
    xsize=new_width,
    ysize=new_height,
    bands=src_ds.RasterCount,
    eType=src_ds.GetRasterBand(1).DataType  # Match input data type
)

# Optional: Copy georeferencing info if you need to preserve it
dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
dst_ds.SetProjection(src_ds.GetProjection())

# Resample and copy the raster data from source to output
gdal.ReprojectImage(
    src_ds,
    dst_ds,
    src_ds.GetProjection(),
    dst_ds.GetProjection(),
    gdal.GRA_NearestNeighbor  # Use GRA_Bilinear/GRA_Cubic for better quality
)

# Properly close datasets to avoid file locks
dst_ds = None
src_ds = None

Quick Fixes to Your Original Code

Just to call out what was off in your initial snippet:

  • You set out_format = "GTiff" instead of "PNG"
  • The CreateCopy parameter order was reversed (it should be driver.CreateCopy(output_path, input_dataset))
  • There was no logic to resize the image or handle resampling

内容的提问来源于stack exchange,提问作者KcFnMi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:25:13