Created
May 17, 2020 15:25
-
-
Save gabriel-fallen/89035dc77b5f8244fd671339a47dd255 to your computer and use it in GitHub Desktop.
Bluring images with GPU.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"/> | |
<title>GPU.js — blur</title> | |
<script src="gpu-browser.min.js"></script> | |
</head> | |
<body> | |
<input id="image" type="file" accept="image/*"> | |
<p>Original:</p> | |
<div id="orig"></div> | |
<p>Processed:</p> | |
<div id="out"></div> | |
<script> | |
const mat = [ | |
[0, 0, 0, 5, 0, 0, 0], | |
[0, 5, 18, 32, 18, 5, 0], | |
[0, 18, 64, 100, 64, 18, 0], | |
[5, 32, 100, 100, 100, 32, 5], | |
[0, 18, 64, 100, 64, 18, 0], | |
[0, 5, 18, 32, 18, 5, 0], | |
[0, 0, 0, 5, 0, 0, 0] | |
]; | |
function covolution(mat, image) { | |
const width = this.constants.width, | |
height = this.constants.height, | |
size = this.constants.mat_size, | |
size2 = Math.floor(size/2); | |
// const pixel = image[this.thread.y][this.thread.x]; | |
let pixel = [0.0, 0.0, 0.0]; | |
for (let j = -size2; j <= size2; j++) { | |
const mat_y = size2 + j; | |
const py = this.thread.y + j; | |
if (py < 0 || py >= height) continue; | |
for (let i = -size2; i <= size2; i++) { | |
const mat_x = size2 + i; | |
const px = this.thread.x + i; | |
if (px < 0 || px >= width) continue; | |
const p = image[py][px]; | |
const m = mat[mat_y][mat_x]; | |
pixel[0] += m*p[0]; | |
pixel[1] += m*p[1]; | |
pixel[2] += m*p[2]; | |
} | |
} | |
// Normalization | |
pixel[0] /= this.constants.n; | |
pixel[1] /= this.constants.n; | |
pixel[2] /= this.constants.n; | |
this.color(pixel[0], pixel[1], pixel[2]); | |
} | |
const gpu = new GPU(); | |
const image = document.getElementById('image'); | |
function processImage() { | |
if (image.files.length === 0) return; | |
const file = image.files[0]; | |
const img = document.createElement("img"); | |
img.onload = () => { | |
const orig = document.getElementById('orig'); | |
orig.firstChild && orig.removeChild(orig.firstChild); | |
orig.appendChild(img); | |
const kernel = gpu.createKernel(covolution) | |
.setConstants({ | |
width: img.width, | |
height: img.height, | |
mat_size: mat.length, | |
n: mat.reduce((a, r) => a + r.reduce((a, x) => a + x, 0), 0) | |
}) | |
.setGraphical(true) | |
.setOutput([img.width, img.height]); | |
kernel(mat, img); | |
// Result: colorful image | |
const out = document.getElementById('out'); | |
out.firstChild && out.removeChild(out.firstChild); | |
out.appendChild(kernel.canvas); | |
}; | |
img.src = URL.createObjectURL(file); | |
} | |
image.addEventListener('change', processImage); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment