Published
Edited
Apr 26, 2022
4 forks
Importers
32 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
extractImageData = (image) => {
const width = image.naturalWidth; // retrieves the image's width
const height = image.naturalHeight; // retrieves the image's height
const context = DOM.context2d(width, height, 1); // create a canvas
context.drawImage(image, 0, 0); // draw the image
const {data} = context.getImageData(0, 0, width, height); // extract pixel data. this will return an array with a length = width * height (pixels) * 4 (it's four because by default, it's providing the red, green, blue and alpha value for each pixel)

// This is for the bins that we will use to group pixel colors together
const range = d3.range(0, 1, 1 / nBins);
// The Quantize Scale allows us to bin values. The domain is set to the [0, 255], the extent of values for RGBA (red, green, blue, alpha)
const bins = ({
r: d3.scaleQuantize().domain([0, 255]).range(range),
g: d3.scaleQuantize().domain([0, 255]).range(range),
b: d3.scaleQuantize().domain([0, 255]).range(range),
})

const pixelData = []; // create an empty array
let r = 0, g = 0, b = 0, a = 0;
for (let i = 0; i < data.length; i += 4) { // For every four datapoints = RGBA
r = data[i + 0];
g = data[i + 1];
b = data[i + 2];
a = data[i + 3];
const rgba = `rgba(${r}, ${g}, ${b}, ${a})`; // Get RGBA value
const hsl = d3.hsl(rgba); // Get HSL value
const rBin = bins.r(r); // Bin R
const gBin = bins.g(g); // Bin G
const bBin = bins.b(b); // Bin B
const rgbBinColor = d3.rgb(bins.r.invertExtent(rBin)[0],bins.g.invertExtent(gBin)[0], bins.b.invertExtent(bBin)[0]) // Create new color from the binned values
pixelData.push({ // Push all the data
r: r,
g: g,
b: b,
a: a,
h: hsl.h,
s: hsl.s,
l: hsl.l,
rgba: rgba,
hex: d3.color(rgba).hex(),
hsl: hsl,
rBin: rBin,
gBin: gBin,
bBin: bBin,
rgbBinR: rgbBinColor.r,
rgbBinG: rgbBinColor.g,
rgbBinB: rgbBinColor.b,
rgbBinColor: rgbBinColor.toString()
})
}
return {
width: width,
height: height,
pixelData: pixelData
}
}
Insert cell
Insert cell
imagePixelData = extractImageData(image)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more