1#!/usr/bin/env python3
2# ******************************************************************************
3#  $Id: pct2rgb.py e67623101c7ab2ec927fbddac12b0410dc3ebf90 2021-10-02 15:44:59 +0200 Andrea Giudiceandrea $
4#
5#  Name:     pct2rgb
6#  Project:  GDAL Python Interface
7#  Purpose:  Utility to convert paletted images into RGB (or RGBA) images.
8#  Author:   Frank Warmerdam, warmerdam@pobox.com
9#
10# ******************************************************************************
11#  Copyright (c) 2001, Frank Warmerdam
12#  Copyright (c) 2009-2010, Even Rouault <even dot rouault at spatialys.com>
13#  Copyright (c) 2020, Idan Miara <idan@miara.com>
14#
15#  Permission is hereby granted, free of charge, to any person obtaining a
16#  copy of this software and associated documentation files (the "Software"),
17#  to deal in the Software without restriction, including without limitation
18#  the rights to use, copy, modify, merge, publish, distribute, sublicense,
19#  and/or sell copies of the Software, and to permit persons to whom the
20#  Software is furnished to do so, subject to the following conditions:
21#
22#  The above copyright notice and this permission notice shall be included
23#  in all copies or substantial portions of the Software.
24#
25#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26#  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
31#  DEALINGS IN THE SOFTWARE.
32# ******************************************************************************
33
34import sys
35import numpy as np
36
37from osgeo import gdal
38from osgeo_utils.auxiliary.util import GetOutputDriverFor, open_ds
39from osgeo_utils.auxiliary.color_palette import get_color_palette
40from osgeo_utils.auxiliary.color_table import get_color_table
41
42progress = gdal.TermProgress_nocb
43
44
45def Usage():
46    print('Usage: pct2rgb.py [-of format] [-b <band>] [-rgba] source_file dest_file')
47    return 1
48
49
50def main(argv):
51    driver = None
52    src_filename = None
53    dst_filename = None
54    pct_filename = None
55    out_bands = 3
56    band_number = 1
57
58    argv = gdal.GeneralCmdLineProcessor(argv)
59    if argv is None:
60        return 0
61
62    # Parse command line arguments.
63    i = 1
64    while i < len(argv):
65        arg = argv[i]
66
67        if arg == '-of' or arg == '-f':
68            i = i + 1
69            driver = argv[i]
70
71        elif arg == '-ct':
72            i = i + 1
73            pct_filename = argv[i]
74
75        elif arg == '-b':
76            i = i + 1
77            band_number = int(argv[i])
78
79        elif arg == '-rgba':
80            out_bands = 4
81
82        elif src_filename is None:
83            src_filename = argv[i]
84
85        elif dst_filename is None:
86            dst_filename = argv[i]
87
88        else:
89            return Usage()
90
91        i = i + 1
92
93    if dst_filename is None:
94        return Usage()
95
96    _ds, err = doit(src_filename, pct_filename, dst_filename, band_number, out_bands, driver)
97    return err
98
99
100def doit(src_filename, pct_filename, dst_filename, band_number=1, out_bands=3, driver=None):
101    # Open source file
102    src_ds = open_ds(src_filename)
103    if src_ds is None:
104        print('Unable to open %s ' % src_filename)
105        return None, 1
106
107    src_band = src_ds.GetRasterBand(band_number)
108
109    # ----------------------------------------------------------------------------
110    # Ensure we recognise the driver.
111
112    if driver is None:
113        driver = GetOutputDriverFor(dst_filename)
114
115    dst_driver = gdal.GetDriverByName(driver)
116    if dst_driver is None:
117        print('"%s" driver not registered.' % driver)
118        return None, 1
119
120    # ----------------------------------------------------------------------------
121    # Build color table.
122
123    if pct_filename is not None:
124        pal = get_color_palette(pct_filename)
125        if pal.has_percents():
126            min_val = src_band.GetMinimum()
127            max_val = src_band.GetMinimum()
128            pal.apply_percent(min_val, max_val)
129        ct = get_color_table(pal)
130    else:
131        ct = src_band.GetRasterColorTable()
132
133    ct_size = ct.GetCount()
134    lookup = [np.arange(ct_size),
135              np.arange(ct_size),
136              np.arange(ct_size),
137              np.ones(ct_size) * 255]
138
139    if ct is not None:
140        for i in range(ct_size):
141            entry = ct.GetColorEntry(i)
142            for c in range(4):
143                lookup[c][i] = entry[c]
144
145    # ----------------------------------------------------------------------------
146    # Create the working file.
147
148    if driver.lower() == 'gtiff':
149        tif_filename = dst_filename
150    else:
151        tif_filename = 'temp.tif'
152
153    gtiff_driver = gdal.GetDriverByName('GTiff')
154
155    tif_ds = gtiff_driver.Create(tif_filename, src_ds.RasterXSize, src_ds.RasterYSize, out_bands)
156
157
158    # ----------------------------------------------------------------------------
159    # We should copy projection information and so forth at this point.
160
161    tif_ds.SetProjection(src_ds.GetProjection())
162    tif_ds.SetGeoTransform(src_ds.GetGeoTransform())
163    if src_ds.GetGCPCount() > 0:
164        tif_ds.SetGCPs(src_ds.GetGCPs(), src_ds.GetGCPProjection())
165
166    # ----------------------------------------------------------------------------
167    # Do the processing one scanline at a time.
168
169    progress(0.0)
170    for iY in range(src_ds.RasterYSize):
171        src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)
172
173        for iBand in range(out_bands):
174            band_lookup = lookup[iBand]
175
176            dst_data = np.take(band_lookup, src_data)
177            tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)
178
179        progress((iY + 1.0) / src_ds.RasterYSize)
180
181    # ----------------------------------------------------------------------------
182    # Translate intermediate file to output format if desired format is not TIFF.
183
184    if tif_filename == dst_filename:
185        dst_ds = tif_ds
186    else:
187        dst_ds = dst_driver.CreateCopy(dst_filename or '', tif_ds)
188        tif_ds = None
189        gtiff_driver.Delete(tif_filename)
190
191    return dst_ds, 0
192
193
194if __name__ == '__main__':
195    sys.exit(main(sys.argv))
196