PROWAREtech
.NET: Access the Pixels of an Image Using SixLabors.ImageSharp v3.x
How to access each pixel's color information using SixLabors.ImageSharp, written in C#.
It may be necessary to access the color information of as image, such as preparing data for a convolutional neural network.
See how to crop an image to a square.
using SixLabors.ImageSharp;
const int IMAGE_WIDTH = 28;
const int IMAGE_HEIGHT = 28;
var inputs = new double[IMAGE_WIDTH, IMAGE_HEIGHT];
using (var bmp = Image.Load<Rgb24>("file.jpg"))
{
if (bmp.Width != IMAGE_WIDTH || bmp.Height != IMAGE_HEIGHT)
bmp.Mutate(x => x.Resize(IMAGE_WIDTH, IMAGE_HEIGHT));
bmp.ProcessPixelRows(accessor =>
{
for (int y = 0; y < IMAGE_HEIGHT; y++)
{
Span pixelRow = accessor.GetRowSpan(y);
for (int x = 0; x < IMAGE_WIDTH; x++)
{
ref Rgb24 pixel = ref pixelRow[x];
inputs[x, y] = 1 - (pixel.R + pixel.G + pixel.B) / 3 / 255.0; // NOTE: convert to B&W
}
}
});
}
using SixLabors.ImageSharp;
const int IMAGE_WIDTH = 28;
const int IMAGE_HEIGHT = 28;
var inputs = new double[IMAGE_WIDTH, IMAGE_HEIGHT];
using (var bmp = Image.Load<Rgb24>("file.jpg"))
{
if (bmp.Width != IMAGE_WIDTH || bmp.Height != IMAGE_HEIGHT)
bmp.Mutate(x => x.Resize(IMAGE_WIDTH, IMAGE_HEIGHT));
bmp.ProcessPixelRows(accessor =>
{
for (int y = 0; y < IMAGE_HEIGHT; y++)
{
Span pixelRow = accessor.GetRowSpan(y);
for (int x = 0; x < IMAGE_WIDTH; x++)
{
ref Rgb24 pixel = ref pixelRow[x];
inputs[x, y] = 1 - (pixel.R * 0.299 + pixel.G * 0.587 + pixel.B * 0.114) / 255.0; // NOTE: matches human perception for B&W images
}
}
});
}
Comment