Skip to content
Open
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
9 changes: 7 additions & 2 deletions tfjs-backend-wasm/src/cc/kernels/CropAndResize.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <emscripten.h>
#endif

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstring>
Expand Down Expand Up @@ -119,11 +120,15 @@ void CropAndResize(size_t images_id, size_t boxes_id, size_t box_ind_id,
const float x2 = *boxes_buf;
boxes_buf++;

if (*box_ind_buf >= batch) {
if (*box_ind_buf < 0 || static_cast<size_t>(*box_ind_buf) >= batch) {
float* out_buf_ptr = out_buf + b * output_strides[0];
std::fill(out_buf_ptr, out_buf_ptr + output_strides[0], 0.0f);
box_ind_buf++;
continue;
}

const size_t box_offset = *box_ind_buf * images_strides[0];
const size_t box_offset =
static_cast<size_t>(*box_ind_buf) * images_strides[0];

const float height_scale =
(crop_height > 1) ? (y2 - y1) * image_height_m1 / (crop_height - 1) : 0;
Expand Down
20 changes: 20 additions & 0 deletions tfjs-backend-wasm/src/index_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,26 @@ describeWithFlags('wasm read/write', ALL_ENVS, () => {
test_util.expectArraysClose(await t.data(), view);
});

it('cropAndResize zero-fills out-of-range box indices', async () => {
const image = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const boxes = tf.tensor2d([
0, 0, 1, 1,
0, 0, 1, 1,
], [2, 4]);
const boxInd = tf.tensor1d([999, -1], 'int32');

const output =
tf.image.cropAndResize(image, boxes, boxInd, [4, 4], 'nearest', -7);

expect(output.shape).toEqual([2, 4, 4, 1]);
test_util.expectArraysClose(await output.data(), new Float32Array(32));

image.dispose();
boxes.dispose();
boxInd.dispose();
output.dispose();
});

// TODO(mattSoulanille): Re-enable this once it's working on iOS.
// tslint:disable-next-line: ban
xit('allocates more than two gigabytes', async () => {
Expand Down