2012-08-09 57 views
6

我想計算一個黑色和白色圖像像素的有符號距離場,但我想我已經設法讓我的代碼在某處出錯。由於這是我的輸入和輸出:計算一個二維帶符號距離場

輸入

Input

輸出

Output

我遇到的問題是在S中間的黑線,我理解讓我相信它應該完全是淺灰色的?

這是我使用的代碼:

for (int x = 0; x < source.width; ++x) 
    { 
     for(int y = 0; y < source.height; ++y) 
     { 
      // Get pixel 
      float a = source.GetPixel(x, y).r; 

      // Distance to closest pixel which is the inverse of a 
      // start on float.MaxValue so we can be sure we found something 
      float distance = float.MaxValue; 

      // Search coordinates, x min/max and y min/max 
      int fxMin = Math.Max(x - searchDistance, 0); 
      int fxMax = Math.Min(x + searchDistance, source.width); 
      int fyMin = Math.Max(y - searchDistance, 0); 
      int fyMax = Math.Min(y + searchDistance, source.height); 

      for (int fx = fxMin; fx < fxMax; ++fx) 
      { 
       for (int fy = fyMin; fy < fyMax; ++fy) 
       { 
        // Get pixel to compare to 
        float p = source.GetPixel(fx, fy).r; 

        // If not equal a 
        if (a != p) 
        { 
         // Calculate distance 
         float xd = x - fx; 
         float yd = y - fy; 
         float d = Math.Sqrt((xd * xd) + (yd * yd)); 

         // Compare absolute distance values, and if smaller replace distnace with the new oe 
         if (Math.Abs(d) < Math.Abs(distance)) 
         { 
          distance = d; 
         } 
        } 
       } 
      } 

      // If we found a new distance, otherwise we'll just use A 

      if (distance != float.MaxValue) 
      { 

       // Clamp distance to -/+ 
       distance = Math.Clamp(distance, -searchDistance, +searchDistance); 

       // Convert from -search,+search to 0,+search*2 and then convert to 0.0, 1.0 and invert 
       a = 1f - Math.Clamp((distance + searchDistance)/(searchDistance + searchDistance), 0, 1); 
      } 

      // Write pixel out 
      target.SetPixel(x, y, new Color(a, a, a, 1)); 
     } 
    } 

回答

3

您的罪魁禍首是這個條件語句:

// If not equal a 
if (a != p) 
{ 

這意味着,你只是在最短的距離從一個黑色的像素感興趣一個白色像素,或者如果'a'是白色,那麼您正在尋找最接近的黑色像素。

如果更改測試,只是看到:

if (p == white) 
{ 

那麼你可能會得到你所期望的。

(我沒有測試這個,所以希望它是正確的)。

(另外,如果它是不正確的,它會因爲它不是一個內置在數學類庫方法是不錯的發表您的Math.Clamp方法。)

最後一件事,不確定算法是否希望您將像素與自身進行比較,因此您可能需要考慮嵌套for循環中的像素。

(基本上,你會期望輸出應該看起來像一個完全黑色的圖像,中間有一個白色像素?中間像素的輸出應該是黑色的,因爲沒有附近的白色像素,或者它應該是白色)。