[英]Finding the nearest (geometrically) non-zero value in a map/2d array
我有一個二維數組,表示來自圖片的選擇性數據。 所有無用的數據都設置為0。從兩個索引中,我需要找到最接近的值-幾何上-到索引(代表坐標)不為0的值。
到目前為止,我的方法是以圓為單位檢查以興趣點為中心的值,並在每經過一個沒有非零值的圓通過后增加半徑。
該方法的復雜度似乎是指數級的,並且當最近點的距離超過約25個像素時,程序將花費很長時間。
您對采用其他方法/現有算法有什么建議嗎?
編輯:每個請求,我當前的代碼如下:
int height;
int width;
ushort[,] _2dfat;
private ushort getAssociatedFat(int centerX, int centerY)
{
int radiusmax = (int)Math.Ceiling(Math.Sqrt(Math.Pow(height,2) + Math.Pow(width, 2) + 1));
return getAssociatedFat(1, centerX, centerY,radiusmax);
}
private ushort getAssociatedFat(int radius, int centerX, int centerY,int radiusmax) //RECURSIVE METHOD: requires extensive analysis and testing
{
ushort max=circleSym8(centerX, centerY, radius);
if (max != 0) return max;
else if (radius <= radiusmax)
return getAssociatedFat(radius + 1, centerX, centerY, radiusmax);
else
{
MessageBox.Show("WARNING: empty fat array/image");
return 0;
}
}
private ushort getMax(ushort max, int x, int y)
{
try
{
if (_2dfat[y, x] == 0) return max;
else if (_2dfat[y, x] > max) return _2dfat[y, x];
else return max;
}
catch (IndexOutOfRangeException) { return max; }
}
private ushort circleSym8(int xCenter, int yCenter, int radius)
{
int x, y, r2;
r2 = radius * radius;
ushort max=0;
max=getMax(max, xCenter, yCenter + radius);
max = getMax(max, xCenter, yCenter - radius);
max = getMax(max, xCenter + radius, yCenter);
max = getMax(max, xCenter - radius, yCenter);
y = radius;
x = 1;
y = (int)(Math.Sqrt(r2 - 1) + 0.5);
while (x < y)
{
max = getMax(max, xCenter + x, yCenter + y);
max = getMax(max, xCenter + x, yCenter - y);
max = getMax(max, xCenter - x, yCenter + y);
max = getMax(max, xCenter - x, yCenter - y);
max = getMax(max, xCenter + y, yCenter + x);
max = getMax(max, xCenter + y, yCenter - x);
max = getMax(max, xCenter - y, yCenter + x);
max = getMax(max, xCenter - y, yCenter - x);
x += 1;
y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
}
if (x == y)
{
max = getMax(max, xCenter + x, yCenter + y);
max = getMax(max, xCenter + x, yCenter - y);
max = getMax(max, xCenter - x, yCenter + y);
max = getMax(max, xCenter - x, yCenter - y);
}
return max;
}
您可以將有趣的數據作為點存儲在四叉樹或kd樹中,並以這種方式執行范圍搜索。 這些數據結構已針對您正在執行的查找進行了優化,並會降低每次搜索的復雜性。
我設想了一個足夠的Quadtree實現,它提供了以下內容:
// Given some point in the quadtree, walk upwards and outwards
// returning points found ordered by distance
var nearestNeighbor = quadTree.Neighbors(point)
.OrderBy(pp => point.Distance(pp))
.First();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.