tensorToImage static method
Convert a tensor back to an image (for debugging/visualization).
tensor: (1, 3, H, W) or (3, H, W) normalized tensor
Returns a decoded image.
Implementation
static img.Image tensorToImage(Tensor tensor) {
List<int> shape;
Float32List data;
if (tensor.shape.length == 4) {
shape = [tensor.shape[2], tensor.shape[3]]; // H, W
data = tensor[0].data; // remove batch dim
} else if (tensor.shape.length == 3) {
shape = [tensor.shape[1], tensor.shape[2]]; // H, W
data = tensor.data;
} else {
throw ArgumentError('Expected 3D or 4D tensor, got ${tensor.shape}');
}
final h = shape[0];
final w = shape[1];
final image = img.Image(width: w, height: h);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
final idx = y * w + x;
// Denormalize: value * std + mean, then clamp to [0, 1]
final r = (data[0 * h * w + idx] * std[0] + mean[0]).clamp(0.0, 1.0);
final g = (data[1 * h * w + idx] * std[1] + mean[1]).clamp(0.0, 1.0);
final b = (data[2 * h * w + idx] * std[2] + mean[2]).clamp(0.0, 1.0);
image.setPixelRgb(
x,
y,
(r * 255).round(),
(g * 255).round(),
(b * 255).round(),
);
}
}
return image;
}