# 几种常见计算机图像处理操作的原理及canvas实现

2013-09-21 • 技术文章 • 评论

W矩阵的不同将带来各种不同的炫酷效果，接下来几个部分中我们将举几个典型的例子进行说明。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

function ConvolutionMatrix(input, m, divisor, offset){ var output = document.createElement("canvas").getContext('2d').createImageData(input); var w = input.width, h = input.height; var iD = input.data, oD = output.data; // 对除了边缘的点之外的内部点的 RGB 进行操作，透明度在最后都设为 255 for (var y = 1; y < h-1; y += 1) { for (var x = 1; x < w-1; x += 1) { for (var c = 0; c < 3; c += 1) { var i = (y*w + x)*4 + c; oD[i] = offset +(m[0]*iD[i-w*4-4] + m[1]*iD[i-w*4] + m[2]*iD[i-w*4+4] + m[3]*iD[i-4] + m[4]*iD[i] + m[5]*iD[i+4] + m[6]*iD[i+w*4-4] + m[7]*iD[i+w*4] + m[8]*iD[i+w*4+4]) / divisor; } oD[(y*w + x)*4 + 3] = 255; // 设置透明度为不透明 } } return output; }

1 2 3 4

// 获取像素点数据 var canvas = document.getElementById('myCanvasElt'); var ctx = canvas.getContext('2d'); var canvasData = ctx.getImageData(0, 0, canvas.width, canvas.height);

1 2 3 4 5

canvasData { width: unsigned long, height: unsigned long, data: CanvasPixelArray }

1

ctx.putImageData(canvasData, 0, 0);

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

var canvas = document.getElementById('myCanvasElt'); var ctx = canvas.getContext('2d'); var canvasData = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var x = 0; x < canvasData.width; x++) { for (var y = 0; y < canvasData.height; y++) { var idx = (x + y * canvas.width) * 4; var r = canvasData.data[idx + 0]; var g = canvasData.data[idx + 1]; var b = canvasData.data[idx + 2]; var avg = (r + g + b) / 3; canvasData.data[idx + 0] = avg; canvasData.data[idx + 1] = avg; canvasData.data[idx + 2] = avg; } } ctx.putImageData(canvasData, 0, 0);

1 2 3 4 5 6 7

var offset = 100; //自定义 for (var i=0; i< canvasData.data.length; i+=4) { d[i] += offset; d[i+1] += offset; d[i+2] += offset; d[i+3] = 127; }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

var recResult = ""; var image = document.querySelector("#img1"); var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image, 0, 0); for (var i = 0; i < 4; i++) { var ldString = ""; var getDat = ctx.getImageData(13 * i + 7, 3, 9, 16); var pixels = getDat.data; for (var j = 0,length = pixels.length; j < length; j += 4) { ldString = ldString + (+(pixels[j]*0.3+pixels[j+1]*0.59+pixels[j+2]*0.11>=140)); } var comms = numbers.map(function (value) { return ldString.split("").filter(function(v,index) { return value[index] === v; }).length }); recResult += comms.indexOf(Math.max.apply(null,comms)); } console.log(recResult);

HTML5的canvas对于图形的处理非常方便，很受开发人员的欢迎，更多canvas的应用也有待我们去探索。

851 篇文章39 人订阅

0 条评论

2.6K3

2086

2023

4218

5218

1233

1772

2111

5217

42810