Added image util class

This commit is contained in:
Samuele Lorefice
2025-03-28 21:57:59 +01:00
parent f3f01a2f85
commit ccaae9befd

View File

@@ -55,6 +55,53 @@ public static class ArrayExt {
}
}
public static class ImageUtil {
public static T[,] LoadImage<T>(string path) where T : struct, IEquatable<T> {
var image = new MagickImage(path);
var pixels = image.GetPixels().ToArray();
if (pixels == null) throw new ("Failed to read image.");
T[,] result = new T[image.Width, image.Height];
uint channels = image.ChannelCount;
if(channels > 4) throw new NotSupportedException($"Image has {channels} channels, only 1-4 channels are supported.");
switch (result) {
case float[,] f:
//remainder of index / channels must be 0
var data = pixels.Where((_, i) => i % channels != 0).ToArray();
for (int i = 0; i < image.Width * image.Height; i++) {
int x = (int)(i % image.Width);
int y = (int)(i / image.Width);
result[x, y] = (T)(object)data[i];
}
break;
case Vector2[,]v2:
//can't read 1 channel images
if (channels < 2) throw new NotSupportedException($"Image has {channels} channels, only 2+ channels are supported.");
//remainder of index / channels must be 0 or 1 (2 values)
var data2 = pixels.Where((_, i) => i % channels >= 1).ToArray();
break;
case Vector3[,]v3:
//can't read <2 channel images
if(channels<3) throw new NotSupportedException($"Image has {channels} channels, only 3+ channels are supported.");
//remainder of index / channels must be 0, 1 or 2 (3 values)
var data3 = pixels.Where((_, i) => i % channels >= 2).ToArray();
break;
case Vector4[,]v4:
//can't read <3 channel images
if(channels<4) throw new NotSupportedException($"Image has {channels} channels, only 4+ channels are supported.");
//remainder of index / channels must be between 0 or 3 (4 values)
var data4 = pixels.Where((_, i) => i % channels >= 3).ToArray();
break;
default:
throw new NotSupportedException($"Type {typeof(T)} is not supported.");
}
return result;
}
}
public class Program {
private const float MAX = 65535f;
private const float MIN = 0f;