Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(tiler-sharp): when resampling uint round numbers rather than truncate BM-1178 #3392

Merged
merged 1 commit into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import assert from 'node:assert';
import { describe, it } from 'node:test';

import { CompositionTiff } from '@basemaps/tiler';

import { resizeBilinear } from '../pipeline.resize.js';

describe('resize-bilinear', () => {
it('should round numbers when working with uint arrays', () => {
const ret = resizeBilinear(
{
pixels: new Uint8Array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
depth: 'uint8',
width: 4,
height: 4,
channels: 1,
},
{ source: { width: 4, height: 4 } } as unknown as CompositionTiff,
{ x: 0, y: 0, width: 1, height: 1 },
{ width: 256, height: 256, scale: 123.123123123 },
);

// All values should be rounded to 1 and not truncated down to 0
assert.ok(ret.pixels.every((f) => f === 1));
});
});
12 changes: 10 additions & 2 deletions packages/tiler-sharp/src/pipeline/pipeline.resize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function getOutputBuffer(source: DecompressedInterleaved, target: Size): Decompr
}
}

function resizeBilinear(
export function resizeBilinear(
data: DecompressedInterleaved,
comp: CompositionTiff,
source: BoundingBox,
Expand All @@ -151,6 +151,14 @@ function resizeBilinear(
const maxHeight = Math.min(comp.source.height, data.height) - 2;
const ret = getOutputBuffer(data, target);
const outputBuffer = ret.pixels;

// should numbers be rounded when resampling, with some numbers like uint8 or uint32 numbers
// will be truncated when being set in their typed buffers,
//
// for example: `0.9999` will end up as `0` in a Uint8Array
// Only floats should be left as floating numbers
const needsRounding = !data.depth.startsWith('float');

for (let y = 0; y < target.height; y++) {
const sourceY = Math.min((y + 0.5) * invScale + source.y, maxHeight);
const minY = Math.floor(sourceY);
Expand Down Expand Up @@ -193,7 +201,7 @@ function resizeBilinear(

const pixel = minXMinY * weightA + maxXMinY * weightB + minXMaxY * weightC + maxXMaxY * weightD;

outputBuffer[outPx] = pixel;
outputBuffer[outPx] = needsRounding ? Math.round(pixel) : pixel;
}
}

Expand Down
Loading