This commit is contained in:
2025-11-24 09:54:45 +08:00
parent 503b4a59f0
commit d05c518850
2 changed files with 52 additions and 5 deletions
+2 -1
View File
@@ -1,7 +1,8 @@
using DigitalImageProcessing;
using SkiaSharp;
Segmentation.Run();
Segmentation.Run1(2);
Segmentation.Run2();
//string testImage = @"C:\Users\Surface\Downloads\" + @"1682575881230001.png";
////Alograms.Steps(@"C:\Users\Surface\Downloads\", @"C:\Users\Surface\Downloads\" + @"1682575881230001.png");
+50 -4
View File
@@ -2,15 +2,15 @@
{
internal static class Segmentation
{
public static void Run()
private const float _0 = 1e-6f;
public static void Run1(int thresholdDelta)
{
int thresholdValue = 128;
int thresholdDelta = 5;
float delta = float.MaxValue;
int loopCount = 0;
int[,] grayImage = GLobalTools.GetGrayAsArray(@"C:\Users\Surface\Downloads\OIP.webp");
int[,] grayImage = GLobalTools.GetGrayAsArray(@"C:\Users\Surface\Downloads\Sprite-0001.png");
while (delta > thresholdDelta)
{
@@ -29,9 +29,55 @@
thresholdValue = thres;
Console.WriteLine($"Current Threshold Value: {thres}, Delta: {delta}");
}
Console.WriteLine($"Final Threshold Value: {thresholdValue} found in {loopCount} loops.");
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");
}
}
}