2012-08-09 3 views
6

흑인과 백인 이미지 픽셀의 서명 된 거리 필드를 계산하려고하는데 어딘가에서 코드를 잘못 처리했다고 생각합니다. 이 내 입력 및 출력이므로 :2D 서명 된 거리 필드 계산

입력

Input

출력

Output

나는 데 문제가 S의 중간에 검은 선이다, 내 이해는 나를 완전히 밝은 회색이어야한다고 믿게한다.

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

이 당신에 검은 색 픽셀에서 최단 거리에만 관심이 있다는 것을 의미 :

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

당신의 범인이 조건 문은 다음과 같습니다

내가 사용하고 코드입니다 흰색 픽셀 또는 'a'가 흰색 인 경우 가장 가까운 검정 픽셀을 찾습니다.
if (p == white) 
{ 

그런 다음 당신은 아마 당신이 기대하는 것을 얻을 것이다 :

은 그냥보고 그 테스트를 변경하는 경우.

(필자는이를 테스트하지 않았으므로 정확함).

(그것이 올바른 아니었다면 그것은 Math 클래스의 라이브러리 방법에 내장되지 않습니다 때문에, 당신의 Math.Clamp 방법을 게시 좋을 것이다.)

마지막으로 한가지,하지 알고리즘이 픽셀을 자체적으로 비교하기를 원한다면 중첩 된 for 루프 내에서 픽셀을 고려해야 할 수도 있습니다.

(기본적으로 중간에 하나의 흰색 픽셀이있는 완전히 검은 색 이미지가 나타나야합니까? 가까운 흰색 픽셀이 없기 때문에 가운데 픽셀의 출력이 검정색이어야합니다. 흰색)