Created
July 24, 2025 15:01
-
-
Save bradmartin333/a236d517f944d5e4d3041f67ba083ff9 to your computer and use it in GitHub Desktop.
turn greyscale Int16 data into a red-green heatmap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:typed_data'; | |
import 'package:image/image.dart' as img; | |
const dim = 512; | |
const maxInt16Value = 32767; | |
const maxInt8Value = 255; | |
final Int16List testData = () { | |
final buffer = Int16List(dim * dim); | |
for (var y = 0; y < dim; y++) { | |
for (var x = 0; x < dim; x++) { | |
final value = (x + y) * (maxInt16Value / ((dim - 1) * 2)); | |
buffer[y * dim + x] = value.toInt(); | |
} | |
} | |
return buffer; | |
}(); | |
Future<void> makeHeatmap({int numFilesToUse = 0}) async { | |
final normalizedData = Uint8List(testData.length); | |
for (var i = 0; i < testData.length; i++) { | |
final int16Value = testData[i]; | |
final normalizedDouble = (int16Value / maxInt16Value) * maxInt8Value; | |
normalizedData[i] = normalizedDouble.round().clamp(0, maxInt8Value); | |
} | |
final imageWithPalette = img.Image( | |
width: dim, | |
height: dim, | |
withPalette: true, | |
); | |
final palette = imageWithPalette.palette!; | |
for (var i = 0; i <= maxInt8Value; i++) { | |
final r = i; | |
final g = maxInt8Value - i; | |
const b = 0; | |
palette | |
..set(i, 0, r.clamp(0, maxInt8Value)) | |
..set(i, 1, g.clamp(0, maxInt8Value)) | |
..set(i, 2, b); | |
} | |
for (var y = 0; y < dim; y++) { | |
for (var x = 0; x < dim; x++) { | |
imageWithPalette.setPixelIndex( | |
x, | |
y, | |
normalizedData[y * dim + x], | |
); | |
} | |
} | |
final cmd = img.Command() | |
..image(imageWithPalette) | |
..encodePngFile( | |
'heatmap.png', | |
); | |
await cmd.executeThread(); | |
} | |
Future<void> main(List<String> arguments) async { | |
await makeHeatmap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment