Calculation of a two-dimensional sign field of distance

I am trying to calculate the sign field of the distance of the black-and-white pixels of an image, but I think that I managed to somehow get the code. Since this is my input and output:

Enter

Input

Exit

Output

The problem I am facing is the black line in the middle of S, I understand that it should be completely light gray?

This is the code I'm using:

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)); } } 
+6
source share
1 answer

Your culprit is a condition:

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

This means that you are only interested in the shortest distance from the black pixel to the white pixel, or if "a" is white, then you are looking for the nearest black pixel.

If you change this test, just look:

 if ( p == white ) { 

Then you are likely to get what you expect.

(I have not tested this, so hopefully this is correct).

(Also, if that weren’t the case, it would be nice to publish your Math.Clamp method as it is not a built-in library method in the Math class.)

Last, I'm not sure if the algorithm wants you to compare the pixel with yourself or not, so you might need to consider this in your nested loops.

(basically, what would you expect the result to look like a completely black image with one white pixel in the middle?) if the output of the middle pixel is black, since there are no adjacent white pixels or it should be white.)

+3
source

Source: https://habr.com/ru/post/922511/


All Articles