[英]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: 使用的其他图像会更复杂一些:
Thanks! 谢谢!
Here's how to use context.getImageData to test if the pixel under the mouse is black or white: 以下是如何使用context.getImageData来测试鼠标下的像素是黑色还是白色:
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) 关键是获取图像像素阵列并测试红色,绿色或蓝色组件是否接近255(==如果所有rgb等于255则为白色)
Example code and a Demo: http://jsfiddle.net/m1erickson/Uw3A4/ 示例代码和演示: 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);});
Boundary detection with circles is much easier than that. 用圆圈进行边界检测比这更容易。 Just use the distance formula to determine if an object is within the radius of the circle.
只需使用距离公式来确定对象是否在圆的半径范围内。
d = sqrt((x2 - x1)^2 + (y2-y1)^2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.