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

如何在Python中用GDAL Translate自动缩放并保存为JPG?

Got it, let's break down how to replicate your gdal_translate command behavior perfectly in Python using gdal.Translate!

The Problem Recap

Your CMD command uses -scale without any explicit min/max values, which tells GDAL to automatically calculate the input image's pixel value range, then linearly stretch that range to the default 0-255 (ideal for 8-bit JPEG output). You want to mirror this in Python, but weren't sure how to set scaleParams or related options.

The Solution Code

Here's the exact Python equivalent of your CMD command:

from osgeo import gdal

img_bsq = 'image.bsq'
img_jpg = 'image.jpg'

# Replicate gdal_translate -of JPEG -outsize 10% 10% -scale
gdal.Translate(
    destName=img_jpg,
    srcDS=img_bsq,
    format='JPEG',
    widthPct=10,  # Matches -outsize 10% (width percentage)
    heightPct=10, # Matches -outsize 10% (height percentage)
    scale=True    # Matches bare -scale: auto-calculate input range, stretch to 0-255
)

Key Details Explained

  1. Scaling the Image Size:

    • Instead of hardcoding width=1024, use widthPct=10 and heightPct=10 to mirror the -outsize 10% 10% behavior. This ensures proportional scaling based on the original image's dimensions, just like the CMD command.
  2. Automatic Value Stretching:

    • The scale=True parameter is exactly equivalent to the bare -scale in your CMD command. GDAL will:
      1. Automatically compute the minimum and maximum pixel values of your input image.bsq
      2. Linearly map that input range to the default output range of 0-255 (perfect for JPEG's 8-bit format)
    • If you ever wanted to explicitly define the output range (though you don't need it here), you could use scaleParams=[[]] (empty inner list triggers auto input range calculation, default output 0-255). But scale=True is more readable for this use case.
  3. Multi-Band Images:

    • If your .bsq has multiple bands, scale=True will apply the auto-stretch to every band individually. If you wanted to customize per-band scaling, you could pass scaleParams=[[], [], []] (one empty list per band) to keep auto-calculation for each.

内容的提问来源于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 10:01:09