Skip to content

Commit

Permalink
convert src images to RGBA if band merge requires alpha band
Browse files Browse the repository at this point in the history
  • Loading branch information
olt committed May 20, 2016
1 parent 07a64ce commit 61bf3ad
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
16 changes: 14 additions & 2 deletions mapproxy/image/merge.py
Expand Up @@ -148,6 +148,7 @@ def __init__(self, mode=None):
self.ops = []
self.cacheable = True
self.mode = mode
self.max_band = {}

def add_ops(self, dst_band, src_img, src_band, factor=1.0):
self.ops.append(band_ops(
Expand All @@ -156,6 +157,8 @@ def add_ops(self, dst_band, src_img, src_band, factor=1.0):
src_band=src_band,
factor=factor,
))
# store highest requested band index for each source
self.max_band[src_img] = max(self.max_band.get(src_img, 0), src_band)

def merge(self, sources, image_opts, size=None, bbox=None, bbox_srs=None, coverage=None):
if not sources:
Expand All @@ -166,10 +169,19 @@ def merge(self, sources, image_opts, size=None, bbox=None, bbox_srs=None, covera

# load src bands
src_img_bands = []
for layer_img in sources:
for i, layer_img in enumerate(sources):
img = layer_img.as_image()
if img.mode == 'P':

if i not in self.max_band:
# do not split img if not requested by any op
src_img_bands.append(None)
continue

if self.max_band[i] == 3 and img.mode != 'RGBA':
# convert to RGBA if band idx 3 is requestd (e.g. P or RGB src)
img = img.convert('RGBA')
elif img.mode == 'P':
img = img.convert('RGB')
src_img_bands.append(img.split())

tmp_mode = self.mode
Expand Down
24 changes: 23 additions & 1 deletion mapproxy/test/unit/test_image.py
Expand Up @@ -733,4 +733,26 @@ def test_from_p_merge(self):

img = result.as_image()
eq_(img.mode, 'RGB')
eq_(img.getpixel((0, 0)), (200, 100, 0))
eq_(img.getpixel((0, 0)), (200, 100, 0))

def test_from_mixed_merge(self):
"""
Check merge RGBA bands from image without alpha (mixed)
"""
merger = BandMerger(mode='RGBA')

merger.add_ops(dst_band=0, src_img=0, src_band=2)
merger.add_ops(dst_band=1, src_img=0, src_band=1)
merger.add_ops(dst_band=2, src_img=0, src_band=0)
merger.add_ops(dst_band=3, src_img=0, src_band=3)

img = Image.new('RGB', (10, 10), (0, 100, 200))
src_img = ImageSource(img)

img_opts = ImageOptions('RGBA')
result = merger.merge([src_img], img_opts)

img = result.as_image()
eq_(img.mode, 'RGBA')
eq_(img.getpixel((0, 0)), (200, 100, 0, 255))

0 comments on commit 61bf3ad

Please sign in to comment.