我的图像有很多不重叠的彩色矩形。每个矩形都是一种独特的颜色,我提前知道颜色。 (奇怪的情况,我知道。)我试图找到每个矩形的像素位置和大小,我需要尽可能快。有没有任何有趣的技巧我可以使用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 :(得分: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
如果最小尺寸为3x3,则需要找到20个矩形,图像为100x100: