RGB effects
In computer graphics, color of pixel is commonly used in the RGB model, where color is formed from three or fourth components.
- r - red component
- g - green component
- b - blue component
- a - transparency or alpha channel
You can achieve some effects by changing the color components.
When the component is represented by integers, the maximum and minimum values are 0 and 255, respectively.
When the component is represented by floats, the maximum and minimum values are 0.0 and 1.0, respectively (in OpenGL).
// check components (js snippet)
this.checkWithAlpha = function() {
red = (red > 255) ? 255 : (red < 0 ? 0 : red);
green = (green > 255) ? 255 : (green < 0 ? 0 : green);
blue = (blue > 255) ? 255 : (blue < 0 ? 0 : blue);
alpha = (alpha > 255) ? 255 : (alpha < 0 ? 0 : alpha);
}
contrast
In simple words contrast is the difference between maximum and minimum pixel intensity in an image. Thus for changing contrast you need to change these maximum and minimum values.
// js snippet
// a contrast correction factor
// c in [-255; 255]
this.getContrastFactor = function(c=1){
return (259*(255+c)) / (255*(259-c));
}
this.changeContrast = function(
cf = this.getContrastFactor(1)){
red = Math.trunc(cf * (red-128) +128 );
green = Math.trunc(cf * (green-128) +128 );
blue = Math.trunc(cf * (blue-128) +128 );
}
brightness
You can make an image lighter or darker by adding/subtracting a constant from each color component. Or you can multiply a constant to each color component.
You also can add brightness level in the contrast formula.
// js snippets
this.changeBrightnessAdd = function(c = 1){
red += c;
green += c;
blue += c;
this.check();
}
this.changeBrightnessMull = function(c = 1.1){
red = Math.round (red*c);
green = Math.round (green*c);
blue = Math.round (blue*c);
this.check();
}
this.changeContrastBrightness = function(
cf = this.getContrastFactor(1), b=0){
red = Math.trunc(cf * (red-128) +128 + b);
green = Math.trunc(cf * (green-128) +128 + b);
blue = Math.trunc(cf * (blue-128) +128 + b);
this.check();
}
grayscale
You can get a monochrome image by assigning an arithmetic mean to each color component of a pixel.
// js snippet
this.toGrayscale = function(){
var m = Math.round((red + green + blue) / 3);
m = (m > 255) ? 255 : ((m < 0) ? 0 : m);
red = m;
green = m;
blue = m;
}
inversion
You can get negative image by subtracting from maximum value the current value of color component.
// js snippet
this.toNegative = function(){
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
}
thresholds
From a grayscale image, thresholding can be used to create binary images.
// js snippet
this.setTreshold = function(threshold = 128){
var min = 0;
var max = 255;
red = (red > threshold) ? max : min;
green = (green > threshold) ? max : min;
blue = (blue > threshold) ? max : min;
}
coarsening
// js snippet
this.toCoarse = function(c = 32){
red %= c;
green %= c;
blue %= c;
}