Path: blob/master/node_modules/@jimp/plugin-normalize/src/index.js
1126 views
import { isNodePattern } from '@jimp/utils';12/**3* Get an image's histogram4* @return {object} An object with an array of color occurrence counts for each channel (r,g,b)5*/6function histogram() {7const histogram = {8r: new Array(256).fill(0),9g: new Array(256).fill(0),10b: new Array(256).fill(0)11};1213this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(14x,15y,16index17) {18histogram.r[this.bitmap.data[index + 0]]++;19histogram.g[this.bitmap.data[index + 1]]++;20histogram.b[this.bitmap.data[index + 2]]++;21});2223return histogram;24}2526/**27* Normalize values28* @param {integer} value Pixel channel value.29* @param {integer} min Minimum value for channel30* @param {integer} max Maximum value for channel31* @return {integer} normalized values32*/33const normalize = function(value, min, max) {34return ((value - min) * 255) / (max - min);35};3637const getBounds = function(histogramChannel) {38return [39histogramChannel.findIndex(value => value > 0),40255 -41histogramChannel42.slice()43.reverse()44.findIndex(value => value > 0)45];46};4748/**49* Normalizes the image50* @param {function(Error, Jimp)} cb (optional) a callback for when complete51* @returns {Jimp} this for chaining of methods52*/53export default () => ({54normalize(cb) {55const h = histogram.call(this);5657// store bounds (minimum and maximum values)58const bounds = {59r: getBounds(h.r),60g: getBounds(h.g),61b: getBounds(h.b)62};6364// apply value transformations65this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(66x,67y,68idx69) {70const r = this.bitmap.data[idx + 0];71const g = this.bitmap.data[idx + 1];72const b = this.bitmap.data[idx + 2];7374this.bitmap.data[idx + 0] = normalize(r, bounds.r[0], bounds.r[1]);75this.bitmap.data[idx + 1] = normalize(g, bounds.g[0], bounds.g[1]);76this.bitmap.data[idx + 2] = normalize(b, bounds.b[0], bounds.b[1]);77});7879if (isNodePattern(cb)) {80cb.call(this, null, this);81}8283return this;84}85});868788