2013-07-19 28 views
0

我有许多不重叠的彩色矩形的图像。每个矩形都是独一无二的颜色,我会提前知道颜色。 (奇怪的情况,我知道。)我试图找到每个矩形的像素位置和大小,我需要尽可能快。是否有任何有趣的技巧我可以用RMagick或类似的库来做到这一点,比通过每个像素迭代更容易?使用RMagick查找颜色位置

我目前的计划是沿着线的东西:

for each pixel (moving left-to-right, top-to-bottom): 
    if pixel color's in our list and we haven't seen it yet: 
    save pixel location as starting location for that color 
    else if pixel color's in our list and we've already seen it: 
    save pixel location as ending location for that color 

(是的,我们可以优化并跳过像素的某些地区,如果我们知道他们是在一个矩形。)在循环结束,我们应该有每个矩形的第一个和最后一个像素,我们可以用它来推导出矩形的尺寸。但这对我来说似乎有点难看。

我可以做得更好吗?

+0

您对最小矩形大小有限制吗?一个“矩形”可以是1x1像素吗?如果它们必须更大,您可以使用这些知识进一步优化。 –

回答

1

此答案仅适用于存在最小矩形大小的情况,理想情况下至少为3x3,这样额外的复杂性就会得到回报。

假设最小矩形大小是(m,n),运行您提出的具有该步长大小的算法以获得近似的起点和终点,然后通过逐像素检查来细化这些近似值(在两个L形路径中)两个相对的角落在哪里。您可以证明,这将始终检查比扫描整个图像更少的像素数。

for each pixel (moving left-to-right step m, top-to-bottom step n): 
    if pixel color's in our list and we haven't seen it yet: 
    save pixel location as rough starting location (xs,ys) for that color 
    save pixel location as rough ending location (xe,ye) for that color 
    else if pixel color's in our list and we've already seen it: 
    save pixel location as rough ending location (xe,ye) for that color 

然后细化位置

for each color 
    with starting location (xs , ys) 
    while color at (xs, ys - 1) is same, update ys = ys - 1 
    while color at (xs - 1, ys) is same, update xs = xs - 1 
    with ending location (xe , ye) 
    while color at (xe, ye + 1) is same, update ye = ye + 1 
    while color at (xe + 1, ye) is same, update xe = xe + 1 

如果最小尺寸为3×3,有20个矩形发现,图像是100×100:

  • 完整扫描将改为10000个像素
  • 优化后的扫描将读取33x33像素,然后通过读取20x10(更多)(平均)来细化20个矩形中的每一个。总计1289个像素。
+0

与步长的好想法!我非常喜欢这个。 – JacobEvelyn