Skip to content

Instantly share code, notes, and snippets.

@gonzaloruizdevilla
Last active September 5, 2019 14:40
Show Gist options
  • Save gonzaloruizdevilla/ff8118168e61fae4027fccab938c8719 to your computer and use it in GitHub Desktop.
Save gonzaloruizdevilla/ff8118168e61fae4027fccab938c8719 to your computer and use it in GitHub Desktop.
function invert(data) {
for (var i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i];
data[i + 1] = 255 - data[i + 1];
data[i + 2] = 255 - data[i + 2];
}
};
function grayscale(data){
for (var i = 0; i < data.length; i += 4) {
const avg = 0.3 * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
data[i] = avg;
data[i + 1] = avg;
data[i + 2] = avg;
}
}
function sepia(data){
for (var i = 0; i < data.length; i += 4) {
const avg = 0.3 * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
data[i] = avg + 100;
data[i + 1] = avg + 50;
data[i + 2] = avg;
}
}
function addConvolveValue(pos, i, data, length){
return pos >= 0 && pos < length ? data[pos] : data[i];
}
function convolve(data, w, offset, v00, v01, v02, v10, v11, v12, v20, v21, v22){
console.log( w, offset, v00, v01, v02, v10, v11, v12, v20, v21, v22)
const divisor = (v00 + v01 + v02 + v10 + v11 + v12 + v20 + v21 + v22) || 1;
const length = data.length;
let res = 0;
let newData = new Uint8Array(length)
for(let i = 0; i < length; i++){
if ((i + 1) % 4 === 0) {
newData[i] = data[i];
continue;
}
let res = v00 * addConvolveValue(i - w * 4 - 4, i, data, length) +
v01 * addConvolveValue(i - w * 4, i, data, length) +
v02 * addConvolveValue(i - w * 4 + 4, i, data, length) +
v10 * addConvolveValue(i - 4, i, data, length) +
v11 * data[i] +
v12 * addConvolveValue(i + 4, i, data, length) +
v20 * addConvolveValue(i + w * 4 - 4, i, data, length) +
v21 * addConvolveValue(i + w * 4 , i, data, length) +
v22 * addConvolveValue(i + w * 4 + 4, i, data, length);
res /= divisor;
res += offset;
newData[i] = res;
}
data.set(newData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment