我尝试使用p5.js进行基于内核的图像处理

时间:2018-08-03 21:17:47

标签: javascript p5.js

var imagething;
var kernel = [[1, 2, 1], [2, 4, 2], [1, 2, 1]];
var sum_of_elements = 0;
var mult_factor = 0.0625;
var bias = 0;

function preload() {
	imagething = loadImage('data/image.png');
}

function setup() {
    createCanvas(1000, 1000);
    imagething.loadPixels();
    image(imagething, 0, 0);
    makeBlurred(imagething, 1);
    image(imagething, 512, 0);
}

function imageIndex(img, x, y) {
    return 4 * (x + y * img.width);
}

function makeBlurred() {
	for(var i = 0; i < kernel.length; i++) {
		for(var j = 0; j < kernel.length; j++) {
			sum_of_elements += kernel[i][j];
		}
	}
	for(var x = 0; x < imagething.width; x++) {
		for(var y = 0; y < imagething.height; y++) {
			var red = 0;
			var green = 0;
			var blue = 0;
			for(var i = 0; i < kernel.length; i++) {
				for(var j = 0; j < kernel.length; j++) {
					var imageX = (x - kernel.length / 2 + i + imagething.width) % imagething.width; 
					var imageY = (y - kernel.length / 2 + j + imagething.height) % imagething.height; 
					var RGB = imageIndex(imagething, imageX, imageY);
					var pix = imagething.pixels;
					var R = pix[RGB];
					var G = pix[RGB + 1];
					var B = pix[RGB + 2];
					console.log("Start: ",R,G,B);
					red += (R * kernel[i][j]);
					green += (G * kernel[i][j]);
					blue += (B * kernel[i][j]);
				}
			}
			var outR;
			var outG;
			var outB;
			outR = Math.min(Math.max(Math.round(red * mult_factor), 0), 255);
			outG = Math.min(Math.max(Math.round(green * mult_factor), 0), 255);
			outB = Math.min(Math.max(Math.round(blue * mult_factor), 0), 255);
			console.log("End: ", outR, outG, outB);
			pix[RGB] = outR;
			pix[RGB + 1] = outG;
			pix[RGB + 2] = outB;
			imagething.updatePixels();
		}
	}
}

因此,我在基于内核的图像处理上引用了this blog post,并且试图模糊图像。我使用的是模糊矩阵,使用的是original图像,结果应该像this一样,但最终却像this一样,所以我必须做错了什么。非常感谢您的帮助:)

0 个答案:

没有答案