我能想到的唯一方法是緩衝最大像素值及其找到的行,以便您只需對內核大小進行完整迭代行/列當最大值不再在它下面時。
在下面的類C的僞代碼中,我假設符號整數,第2行主陣列用於源和目的地和通過矩形內核[± DX,± DY]。
//initialise the maxima and their row positions
for(x=0; x < nx; ++x)
{
row[x] = -1;
buf[x] = 0;
}
for(sy=0; sy < ny; ++sy)
{
//update the maxima and their row positions
for(x=0; x < nx; ++x)
{
if(row[x] < max(sy-dy, 0))
{
//maximum out of scope, search column
row[x] = max(sy-dy, 0);
buf[x] = src[row[x]][x];
for(y=row[x]+1; y <= min(sy+dy, ny-1); ++y)
{
if(src[y][x]>=buf[x])
{
row[x] = y;
buf[x] = src[y][x];
}
}
}
else
{
//maximum in scope, check latest value
y = min(sy+dy, ny-1);
if(src[y][x] >= buf[x])
{
row[x] = y;
buf[x] = src[y][x];
}
}
}
//initialise maximum column position
col = -1;
for(sx=0; sx < nx; ++sx)
{
//update maximum column position
if(col<max(sx-dx, 0))
{
//maximum out of scope, search buffer
col = max(sx-dx, 0);
for(x=col+1; x <= min(sx+dx, nx-1); ++x)
{
if(buf[x] >= buf[col]) col = x;
}
}
else
{
//maximum in scope, check latest value
x = min(sx+dx, nx-1);
if(buf[x] >= buf[col]) col = x;
}
//assign maximum to destination
dest[sy][sx] = buf[col];
}
}
當源從右下方左到最小的頂部的最大順利,迫使一個完整的行或列掃描在每個步驟(儘管它仍比更有效時會發生最壞情況下的性能原始嵌套循環)。
雖然我認爲平均情況下性能會好得多,因爲包含增加值(包括行和列)的區域將在需要掃描前更新最大值。這就是說,沒有經過實際測試,我建議你運行一些基準測試,而不是相信我的直覺。
這不是一個完整的解決方案,只是一個想法:我認爲操作是可分解的,即通過在一行中執行3x1擴展和1x3擴展可以獲得3x3擴張,這種擴展速度要快得多。 1x9擴張可以分解爲兩個1x3擴張。 (我知道這對於高斯模糊是正確的,但我不確定它是否適用於侵蝕/膨脹。) – HugoRune