Search code examples
pythonimageimage-processingimagemagickgdal

Replace transparency with whitebackground in BigTiff


I am working with python to convert an RGBA tiff to an RGB tiff with a white background.

I am using the library ImageMagick and GDAL.

My code looks like that:

def add_background_to_rgba_geotiff(source, destination):

convert_rgba_to_rgb_tif(source, destination)
add_metadata_to_new_geotiff_file(source, destination)


def convert_rgba_to_rgb_tif(source, destination):
    # work also with BigTiff
    command = ' '.join(['convert', quote(source),
                        '-background', 'white',
                        '-alpha', 'background',
                        '-alpha', 'off', quote(destination)])
    shell_command.execute_and_log_outputs(command, shell=True)


def add_metadata_to_new_geotiff_file(source, destination):
    RGBA_tif = gdal.Open(source, gdalconst.GA_ReadOnly)
    RGB_tif = gdal.Open(destination, gdalconst.GA_Update)

    RGB_tif.SetMetadata(RGBA_tif.GetMetadata())
    RGB_tif.SetGeoTransform(RGBA_tif.GetGeoTransform())
    RGB_tif.SetProjection(RGBA_tif.GetProjection())

    del (RGBA_tif)
    del (RGB_tif)

def execute_and_log_outputs(command, silence_errors=False, **kwargs):
    shell_process = execute_async(command,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE,
                                  **kwargs)

     (out, err) = shell_process.communicate()

When I try to run my code with a tiff everything happens well but when I want to apply that on a BigTIFF (>4GB) it fails with this error:

TIFFWriteDirectoryTagData: Maximum TIFF file size exceeded.

Does someone know how to use BigTiff with ImageMagick? Or could it be possible to do that with GDAL? For the moment when I try with GDAL, I only achieved to have a black background.

Thanks for your help.


Solution

  • If you check the available formats that ImageMagick knows, you will see a TIFF64:

    identify -list format | grep -i tiff
    
          EPT  EPT       rw-   Encapsulated PostScript with TIFF preview
         EPT2  EPT       rw-   Encapsulated PostScript Level II with TIFF preview
         EPT3  EPT       rw+   Encapsulated PostScript Level III with TIFF preview
       GROUP4* TIFF      rw-   Raw CCITT Group4
         PTIF* TIFF      rw+   Pyramid encoded TIFF
         TIFF* TIFF      rw+   Tagged Image File Format (LIBTIFF, Version 4.0.9)
       TIFF64* TIFF      rw-   Tagged Image File Format (64-bit) (LIBTIFF, Version 4.0.9)
    

    If you try to make a TIFF like this it fails:

    convert -size 20000x50000 xc:red +noise random a.tif
    convert: Maximum TIFF file size exceeded. `TIFFAppendToStrip' @ error/tiff.c/TIFFErrors/652.
    

    So, force the TIFF64 delegate by prepending it to the output filename to get a BigTIFF like this:

    convert -size 20000x50000 xc:red +noise random TIFF64:a.tif
    

    and it works.