Files
DigitalImageProcessing/DigitalImageProcessing/GLobalTools.cs
T
2025-11-17 10:32:51 +08:00

91 lines
3.3 KiB
C#

using SkiaSharp;
namespace DigitalImageProcessing
{
internal static class GLobalTools
{
public static SKBitmap GetFull(string filepath) => SKBitmap.Decode(filepath);
public static SKBitmap GetGray(string filepath)
{
SKBitmap src = SKBitmap.Decode(filepath);
Parallel.For(0, src.Height - 1, (y) =>
Parallel.For(0, src.Width - 1, (x) =>
{
SKColor color = src.GetPixel(x, y);
byte avg = (byte)((color.Red + color.Green + color.Blue) / 3);
src.SetPixel(x, y, new(avg, avg, avg));
})
);
return src;
}
public static SKBitmap GetBinary(string filepath)
{
SKBitmap src = SKBitmap.Decode(filepath);
Parallel.For(0, src.Height - 1, (y) =>
Parallel.For(0, src.Width - 1, (x) =>
{
SKColor color = src.GetPixel(x, y);
byte bin = (byte)((color.Red + color.Green + color.Blue) / 3 > 128 ? 256 : 0);
src.SetPixel(x, y, new(bin, bin, bin));
})
);
return src;
}
public static int[,] GetGrayAsArray(string filepath)
{
SKBitmap src = SKBitmap.Decode(filepath);
int[,] result = new int[src.Width, src.Height];
Parallel.For(0, src.Height - 1, (y) =>
Parallel.For(0, src.Width - 1, (x) =>
{
SKColor color = src.GetPixel(x, y);
byte avg = (byte)((color.Red + color.Green + color.Blue) / 3);
result[x, y] = avg;
})
);
return result;
}
public static T[,] Select<T>(this T[,] array, Func<T, T> func)
{
int width = array.GetLength(0);
int height = array.GetLength(1);
T[,] result = new T[width, height];
Parallel.For(0, height - 1, (y) =>
Parallel.For(0, width - 1, (x) =>
{
result[x, y] = func(array[x, y]);
})
);
return result;
}
public static T[,] Select<T>(this T[,] array, Func<T, int, int, T> func)
{
int width = array.GetLength(0);
int height = array.GetLength(1);
T[,] result = new T[width, height];
Parallel.For(0, height - 1, (y) =>
Parallel.For(0, width - 1, (x) =>
{
result[x, y] = func(array[x, y], x, y);
})
);
return result;
}
public static void Save(this int[,] array, string filepath)
{
int width = array.GetLength(0);
int height = array.GetLength(1);
using SKBitmap output = new(width, height);
Parallel.For(0, height - 1, (y) =>
Parallel.For(0, width - 1, (x) =>
{
byte val = (byte)array[x, y];
output.SetPixel(x, y, new SKColor(val, val, val));
})
);
using FileStream fs = new(filepath, FileMode.Create, FileAccess.Write);
output.Encode(fs, SKEncodedImageFormat.Png, 100);
}
}
}