2

I want to ask how to convert PNG to GeoTIFF using GDAL in Python. I ran this code but it's not work and I want to export the output into my computer.

How can I fix my code?

ds = gdal.Open('input.png')
gt = gdal.Translate(ds, 'output.tif', projWin = [-180, 90, 180, -90])
gt = None
3
  • 1
    Welcome to GIS SE! We're a little different from other sites; this isn't a discussion forum but a Q&A site. Your questions should as much as possible describe not just what you want to do, but precisely what you have tried and where you are stuck trying that. Please check out our short tour for more about how the site works
    – Ian Turton
    Feb 10, 2022 at 8:46
  • 3
    what happens when you run that? does your png file have a world file with it? what is output?
    – Ian Turton
    Feb 10, 2022 at 8:47
  • nothing happen when i ran my code, but i'm not get the output too. The output is tiff Feb 10, 2022 at 8:51

2 Answers 2

8

I'm assuming that your PNG file doesn't have geolocation information embedded but you know what the corners of the data. I think you just had the wrong option for gdal.Translate. Check this out using a random example image that should span the same extent as you had in your example. I also assume that it is in WGS84 Latitude/Longitude (not quite for my example)

inp = "/vsicurl/https://upload.wikimedia.org/" + \ 
      "wikipedia/commons/thumb/2/23/" + \ 
      "Blue_Marble_2002.png/" + \
      "450px-Blue_Marble_2002.png"
ds = gdal.Open(inp)
gt = gdal.Translate(ds, 'output.tif',
                    outputBounds = [-180, 90, 180, -90],
                    outputSRS="EPSG:4326"
                    )
gt = None
0
5

I know that the OP specifically asked for a gdal solution but may I offer another solution that works better for me ?

Here I'm using the rasterIo lib (available on both pipy and conda) to read the png, extract band information and build the output file. As it's more pythonic, I think if something goes wrong you'll have more error logs to help you.

import rasterio as rio 

dataset = rio.open('input.png')
bands = [1, 2, 3] # I assume that you have only 3 band i.e. no alpha channel in your PNG
data = dataset.read(bands)

# create the output transform
west, south, east, north = (-180, -90, 180, 90)
transform = rio.transform.from_bounds(
    west, 
    south, 
    east, 
    north, 
    data.shape[1], 
    data.shape[2]
)

# set the output image kwargs
kwargs = {
    "driver": "GTiff",
    "width": data.shape[1], 
    "height": data.shape[2],
    "count": len(bands), 
    "dtype": data.dtype, 
    "nodata": 0,
    "transform": transform, 
    "crs": "EPSG:4326"
}

with rio.open("output.tiff", "w", **kwargs) as dst:
    dst.write(data, indexes=bands)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.