【问题标题】:Determine the distance between black and white pixels in Javascript在Javascript中确定黑白像素之间的距离
【发布时间】:2013-04-18 15:08:20
【问题描述】:

我计划在这个项目中使用 JavaScript(但我愿意使用其他东西)。我在 javascript 中加载图像,当我在图像上放置一个点时,我想计算从放置的点到第一个黑色或灰色像素的 x 和 y 距离。

所以我将红点放在图像上,然后我想向用户显示从所选点到第一个黑色像素的 x、y 距离。距离可以以像素为单位(我不介意)。这可能吗?有人可以帮我吗?

谢谢!

【问题讨论】:

    标签: javascript image-processing


    【解决方案1】:

    另一种方法是按照@Joseph the Dreamer 的建议再次使用getImageData 函数,但您可以执行以下操作而不是搜索方向:

    // the context to the canvas which holds your map
    var ctx {...};
    
    var point = {x:x, y:y};
    // this gets a 3 by 3 bitmap data from your canvas with the centre being your point
    var search = ctx.getImageData(x - 1, y - 1, 3, 3);
    
    var match = false;
    while(!match)
    {
        // iterate over the search array looking for a black or grey pixel
        // and add the co ordinates of the matches into another array
    
        // if we found matches in this loop, calculate the shortest length match
        // and then break out of the loop
    
        // otherwise get a bigger sample data to search through and do this loop again
        // you could optimise this by skipping the pixels you looked through
        // in the previous loop
    }
    

    【讨论】:

    • 感谢您的建议!
    【解决方案2】:

    您可以使用drawImage 将图像绘制到画布上,如MDN example. 所示,然后使用getImageData 提取像素数据,它返回一个包含widthheightdata 的对象属性。

    data 属性是一系列 rgba(红色、绿色、蓝色、alpha)值,每行像素从左到右运行。数值范围为 0-255。对于透明度,0 表示像素透明,255 表示不透明。

    数组如下所示:

        ,--- first pixel (top left)
        |       ,-- second pixel
    ____|___ ___|___    _______,--- last pixel (bottom right)
    [r,g,b,a,r,g,b,a...,r,g,b,a]
    

    鉴于画布上下文的宽度和高度,您可以使用一些不那么复杂的数学来获取 (x,y) 处的像素,或者只是运行一些嵌套循环,您可以在任何给定的 (x ,y)。

    至于寻找最近的黑色像素,我建议您从 (x,y) 处的像素开始,然后递增/递减 x,y 或两者兼而有之,以获得周围的像素。我能想到的最快的方法是在一个方向上穿过像素,直到你碰到你想要的像素。对其他方向执行此操作。然后比较值。

    在笛卡尔平面中让相邻像素距离“红色像素”1 像素的示例。如果你只想要水平和垂直,你可以省略对角线。

    /*(x-1,y+1)*/ ( x ,y+1) /*(x+1,y+1)*/
      (x-1, y )   ( x , y )   (x+1, y )
    /*(x-1,y-1)*/ ( x ,y-1) /*(x+1,y-1)*/
    

    对于距离,给定“红色像素”的 (x,y) 和最近的黑色像素 (x,y),您可以使用one of many distance formulas

    【讨论】:

    • 感谢您的回答,您知道图书馆或其他东西可以自动执行此操作吗?
    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多