Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@jimp/plugin-normalize/src/index.js
1126 views
1
import { isNodePattern } from '@jimp/utils';
2
3
/**
4
* Get an image's histogram
5
* @return {object} An object with an array of color occurrence counts for each channel (r,g,b)
6
*/
7
function histogram() {
8
const histogram = {
9
r: new Array(256).fill(0),
10
g: new Array(256).fill(0),
11
b: new Array(256).fill(0)
12
};
13
14
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
15
x,
16
y,
17
index
18
) {
19
histogram.r[this.bitmap.data[index + 0]]++;
20
histogram.g[this.bitmap.data[index + 1]]++;
21
histogram.b[this.bitmap.data[index + 2]]++;
22
});
23
24
return histogram;
25
}
26
27
/**
28
* Normalize values
29
* @param {integer} value Pixel channel value.
30
* @param {integer} min Minimum value for channel
31
* @param {integer} max Maximum value for channel
32
* @return {integer} normalized values
33
*/
34
const normalize = function(value, min, max) {
35
return ((value - min) * 255) / (max - min);
36
};
37
38
const getBounds = function(histogramChannel) {
39
return [
40
histogramChannel.findIndex(value => value > 0),
41
255 -
42
histogramChannel
43
.slice()
44
.reverse()
45
.findIndex(value => value > 0)
46
];
47
};
48
49
/**
50
* Normalizes the image
51
* @param {function(Error, Jimp)} cb (optional) a callback for when complete
52
* @returns {Jimp} this for chaining of methods
53
*/
54
export default () => ({
55
normalize(cb) {
56
const h = histogram.call(this);
57
58
// store bounds (minimum and maximum values)
59
const bounds = {
60
r: getBounds(h.r),
61
g: getBounds(h.g),
62
b: getBounds(h.b)
63
};
64
65
// apply value transformations
66
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
67
x,
68
y,
69
idx
70
) {
71
const r = this.bitmap.data[idx + 0];
72
const g = this.bitmap.data[idx + 1];
73
const b = this.bitmap.data[idx + 2];
74
75
this.bitmap.data[idx + 0] = normalize(r, bounds.r[0], bounds.r[1]);
76
this.bitmap.data[idx + 1] = normalize(g, bounds.g[0], bounds.g[1]);
77
this.bitmap.data[idx + 2] = normalize(b, bounds.b[0], bounds.b[1]);
78
});
79
80
if (isNodePattern(cb)) {
81
cb.call(this, null, this);
82
}
83
84
return this;
85
}
86
});
87
88