image-js
Version:
Image processing and manipulation in JavaScript
30 lines • 1.06 kB
JavaScript
import { validateChannel } from '../utils/validators/validators.js';
/**
* Returns a histogram of pixel intensities.
* @param image - The original image.
* @param options - Histogram options.
* @returns - The histogram.
*/
export function histogram(image, options = {}) {
let { channel } = options;
const { slots = 2 ** image.bitDepth } = options;
if (!(slots !== 0 && (slots & (slots - 1)) === 0)) {
throw new RangeError('slots must be a power of 2, for example: 64, 256, 1024');
}
if (typeof channel !== 'number') {
if (image.channels !== 1) {
throw new TypeError('channel option is mandatory for multi-channel images');
}
channel = 0;
}
validateChannel(channel, image);
const hist = new Uint32Array(slots);
let bitShift = 0;
const bitSlots = Math.log2(slots);
bitShift = image.bitDepth - bitSlots;
for (let i = 0; i < image.size; i++) {
hist[image.getValueByIndex(i, channel) >> bitShift]++;
}
return hist;
}
//# sourceMappingURL=histogram.js.map