MCPcopy Create free account
hub / github.com/tensorflow/tfjs-examples / applyColorMap

Function applyColorMap

visualize-convnet/utils.js:138–171  ·  view source on GitHub ↗

* Convert an input monocolor image to color by applying a color map. * * @param {tf.Tensor4d} x Input monocolor image, assumed to be of shape * `[1, height, width, 1]`. * @returns Color image, of shape `[1, height, width, 3]`.

(x)

Source from the content-addressed store, hash-verified

136 * @returns Color image, of shape `[1, height, width, 3]`.
137 */
138function applyColorMap(x) {
139 tf.util.assert(
140 x.rank === 4, `Expected rank-4 tensor input, got rank ${x.rank}`);
141 tf.util.assert(
142 x.shape[0] === 1,
143 `Expected exactly one example, but got ${x.shape[0]} examples`);
144 tf.util.assert(
145 x.shape[3] === 1,
146 `Expected exactly one channel, but got ${x.shape[3]} channels`);
147
148 return tf.tidy(() => {
149 // Get normalized x.
150 const EPSILON = 1e-5;
151 const xRange = x.max().sub(x.min());
152 const xNorm = x.sub(x.min()).div(xRange.add(EPSILON));
153 const xNormData = xNorm.dataSync();
154
155 const h = x.shape[1];
156 const w = x.shape[2];
157 const buffer = tf.buffer([1, h, w, 3]);
158
159 const colorMapSize = RGB_COLORMAP.length / 3;
160 for (let i = 0; i < h; ++i) {
161 for (let j = 0; j < w; ++j) {
162 const pixelValue = xNormData[i * w + j];
163 const row = Math.floor(pixelValue * colorMapSize);
164 buffer.set(RGB_COLORMAP[3 * row], 0, i, j, 0);
165 buffer.set(RGB_COLORMAP[3 * row + 1], 0, i, j, 1);
166 buffer.set(RGB_COLORMAP[3 * row + 2], 0, i, j, 2);
167 }
168 }
169 return buffer.toTensor();
170 });
171}
172
173module.exports = {
174 applyColorMap,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected