84 lines
3.1 KiB
C#
84 lines
3.1 KiB
C#
namespace DigitalImageProcessing
|
|
{
|
|
internal static class Segmentation
|
|
{
|
|
private const float _0 = 1e-6f;
|
|
public static void Run1(int thresholdDelta)
|
|
{
|
|
int thresholdValue = 128;
|
|
|
|
float delta = float.MaxValue;
|
|
int loopCount = 0;
|
|
|
|
int[,] grayImage = GLobalTools.GetGrayAsArray(@"C:\Users\Surface\Downloads\Sprite-0001.png");
|
|
|
|
while (delta > thresholdDelta)
|
|
{
|
|
loopCount++;
|
|
List<int> forePix = [], backPix = [];
|
|
for (int i = 0; i < grayImage.GetLength(0); i++)
|
|
for (int j = 0; j < grayImage.GetLength(1); j++)
|
|
if (grayImage[i, j] >= thresholdValue)
|
|
forePix.Add(grayImage[i, j]);
|
|
else
|
|
backPix.Add(grayImage[i, j]);
|
|
int fore = (int)forePix.Average();
|
|
int back = (int)backPix.Average();
|
|
int thres = (fore + back) / 2;
|
|
delta = int.Abs(thres - thresholdValue);
|
|
thresholdValue = thres;
|
|
Console.WriteLine($"Current Threshold Value: {thres}, Delta: {delta}");
|
|
}
|
|
Console.WriteLine($"Threshold Value: {thresholdValue} found in {loopCount} loops.");
|
|
int[,] foreground = grayImage.Select(i => i > thresholdValue ? 255 : 0);
|
|
foreground.Save(@"C:\Users\Surface\Downloads\OIP_foreground.webp");
|
|
}
|
|
public static void Run2()
|
|
{
|
|
int[,] gray = GLobalTools.GetGrayAsArray(@"C:\Users\Surface\Downloads\Sprite-0001.png");
|
|
int[] pixels = new int[254];
|
|
int size = 0;
|
|
|
|
|
|
for (int i = 0; i < gray.GetLength(0); i++)
|
|
for (int j = 0; j < gray.GetLength(1); j++)
|
|
if (gray[i, j] is > 0 and < 255)
|
|
{
|
|
pixels[gray[i, j] - 1]++;
|
|
size++;
|
|
}
|
|
|
|
float[] pws = new float[pixels.Length]; // 类概率
|
|
int mut = 0;
|
|
for (int t = 0; t < pixels.Length; t++)
|
|
{
|
|
pws[t] = (float)pixels[t] / size;
|
|
mut += t * pixels[t];
|
|
}
|
|
|
|
float w0 = 0; // 类内概率
|
|
float mu0 = 0; // 类内均值
|
|
float wxmax = 0; // 类间方差最大值
|
|
int threshold = 0;
|
|
for (int t = 0; t < pixels.Length; t++)
|
|
{
|
|
w0 += pws[t];
|
|
mu0 += t * pws[t];
|
|
float w1 = 1 - w0;
|
|
if (w0 < _0 || w1 < _0) continue;
|
|
float mu1 = (mut - mu0) / w1;
|
|
mu0 /= w0;
|
|
float wx = w0 * w1 * (mu0 / w0 - mu1) * (mu0 / w0 - mu1);
|
|
if (wx > wxmax)
|
|
{
|
|
wxmax = wx;
|
|
threshold = t + 1;
|
|
}
|
|
}
|
|
Console.WriteLine($"Threshold Value: {threshold}");
|
|
int[,] foreground = gray.Select(i => i > threshold ? 255 : 0);
|
|
foreground.Save(@"C:\Users\Surface\Downloads\OIP_foreground.webp");
|
|
}
|
|
}
|
|
}
|