画布黑白图像到形状 [英] Canvas Black and White Image to Shape
问题描述
我目前在画布上加载了一个简单的图片。
I currently have loaded a simple image onto a canvas.
它只是一个黑色背景的白色圆圈。
Its just a white circle with a black background.
我想做的是将白色区域转换为形状。
这个形状将用于边界检测。
What I'm trying to do is convert that white area into a shape. This shape will then be used for boundary detection.
我假设我需要逐个像素地循环图像数据我之前做过颜色操作,但我不知道我如何将这些信息保存到边界和/或超出范围。
I'm assuming that I need to loop through the image data pixel by pixel? I've done this before for color manipulation, but I'm not sure how I would go about saving this information into "in bounds" and / or "out of bounds".
使用的其他图片会更复杂一些:
Other images used will be a bit more complex:
谢谢!
推荐答案
这里是如何使用context.getImageData来测试鼠标下的像素是黑色还是白色:
Here's how to use context.getImageData to test if the pixel under the mouse is black or white:
关键是获取图像像素阵列,并测试任何红色,绿色或蓝色分量接近255(如果所有rgb等于255,则为==白色)
The key is to get the image pixel array and test if any of the red, green or blue components are near 255 (==white if all rgb equal 255)
示例代码和演示: http://jsfiddle.net/m1erickson/Uw3A4/
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var data;
var $results=$("#results");
var img=new Image();
img.onload=start;
img.crossOrigin="anonymous";
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/temp00.png";
function start(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
data=ctx.getImageData(0,0,canvas.width,canvas.height).data;
}
function handleMouseMove(e){
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
var isWhite=(data[(mouseY*canvas.width+mouseX)*4]>200);
$results.text(isWhite?"Inside":"Outside");
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
这篇关于画布黑白图像到形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!