Skip to content

Commit

Permalink
Merge pull request #827 from girder/write-with-mask
Browse files Browse the repository at this point in the history
Fix adding tiles with a mask
  • Loading branch information
manthey authored Apr 15, 2022
2 parents 8f59a04 + b1ac97b commit 51c647b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
6 changes: 4 additions & 2 deletions sources/vips/large_image_source_vips/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,11 @@ def addTile(self, tile, x=0, y=0, mask=None, interpretation=None):
newarr[:, :, :tile.shape[2]] = tile
newarr[:, :, -1] = 255
tile = newarr
if mask:
if mask is not None:
if len(mask.shape) == 3:
mask = numpy.logical_or.reduce(mask, axis=2)
if tile.shape[2] in {2, 4}:
tile[:, :, -1] *= mask.astype(numpy.dtype.bool)
tile[:, :, -1] *= mask.astype(bool)
else:
raise TileSourceError('Cannot apply a mask if the source is not 1 or 3 channels.')
if tile.dtype.char not in dtypeToGValue:
Expand Down
26 changes: 26 additions & 0 deletions test/test_source_vips.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,29 @@ def testNewAndWriteJPEG():
assert image[:len(utilities.JPEGHeader)] == utilities.JPEGHeader
finally:
shutil.rmtree(tmpdir)


def testNewAndWriteWithMask():
imagePath = datastore.fetch('sample_image.ptif')
source = large_image.open(imagePath)
out = large_image_source_vips.new()
for tile in source.tileIterator(
format=large_image.constants.TILE_FORMAT_NUMPY,
region=dict(right=4000, bottom=2000),
):
if tile['tile_position']['position']:
mask = tile['tile'] > 128
else:
mask = None
out.addTile(tile['tile'], x=tile['x'], y=tile['y'], mask=mask)

tmpdir = tempfile.mkdtemp()
outputPath = os.path.join(tmpdir, 'temp.tiff')
try:
out.write(outputPath, lossy=False)
assert os.path.getsize(outputPath) > 50000
result = large_image.open(outputPath)
resultMetadata = result.getMetadata()
assert resultMetadata['sizeX'] == 4000
finally:
shutil.rmtree(tmpdir)

0 comments on commit 51c647b

Please sign in to comment.