Public
Edited
Nov 6, 2020
1 fork
4 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
grayscaleMethods = {
return {
'naive': {
label: 'Naive (averaging)',
func: (r, g, b) => Math.round(r + g + b) / 3,
},
'luma-common': {
label: 'Luminance (common)',
func: (r, g, b) => r * 0.3 + g * 0.59 + b * 0.11,
},
'BT709': {
label: 'Luminance (ITU-R BT.709; luma)',
func: (r, g, b) => r * 0.2126 + g * 0.7152 + b * 0.0722,
},
'BT601': {
label: 'Luminance (ITU-R BT.601)',
func: (r, g, b) => r * 0.299 + g * 0.587 + b * 0.114,
},
'desat': {
label: 'Desaturation',
func: (r, g, b) => Math.round((Math.max(r, g, b) + Math.min(r, g, b)) / 2),
},
'red': {
label: 'Picking only red channel',
func: (r, g, b) => r,
},
'green': {
label: 'Picking only green channel',
func: (r, g, b) => g,
},
'blue': {
label: 'Picking only blue channel',
func: (r, g, b) => b,
},
}
}
Insert cell
grayscaleMethod = grayscaleMethods[selectedGrayscaleMethod]
Insert cell
Insert cell
Insert cell
function toGrayScale(imageData) {
const {width, height, data} = imageData
const result = new Uint8ClampedArray(data.length)
for (let i = 0; i < data.length; i += 4) {
const sub = data.subarray(i, i + 4)
const [r, g, b, a] = sub
const gray = grayscaleMethod.func(r, g, b)
result[i] = gray
result[i+1] = gray
result[i+2] = gray
result[i+3] = a
}
return new ImageData(result, width, height)
}
Insert cell
function renderImageData(imageData) {
const {width, height} = imageData
const ctxNatural = DOM.context2d(image.naturalWidth, image.naturalHeight, 1)
ctxNatural.putImageData(imageData, 0, 0)
const canvas = DOM.canvas(image.width, image.height)
canvas.style.imageRendering = 'high-quality'
const scale = image.clientWidth / image.naturalWidth
const context = canvas.getContext('2d')
context.scale(scale, scale)
context.drawImage(ctxNatural.canvas, 0, 0)
return canvas
}
Insert cell
function getImageData(image, width = image.naturalWidth, height = image.naturalHeight) {
const context = DOM.context2d(width, height, 1);
context.drawImage(image, 0, 0, width, height);
return context.getImageData(0, 0, width, height);
}
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