如何在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
Scaling the Image Size:
- Instead of hardcoding
width=1024, usewidthPct=10andheightPct=10to mirror the-outsize 10% 10%behavior. This ensures proportional scaling based on the original image's dimensions, just like the CMD command.
- Instead of hardcoding
Automatic Value Stretching:
- The
scale=Trueparameter is exactly equivalent to the bare-scalein your CMD command. GDAL will:- Automatically compute the minimum and maximum pixel values of your input
image.bsq - Linearly map that input range to the default output range of 0-255 (perfect for JPEG's 8-bit format)
- Automatically compute the minimum and maximum pixel values of your input
- 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). Butscale=Trueis more readable for this use case.
- The
Multi-Band Images:
- If your
.bsqhas multiple bands,scale=Truewill apply the auto-stretch to every band individually. If you wanted to customize per-band scaling, you could passscaleParams=[[], [], []](one empty list per band) to keep auto-calculation for each.
- If your
内容的提问来源于stack exchange,提问作者KcFnMi
相关产品推荐
相关产品推荐

