问题存储图像矩阵 [英] Problem storing image matrix
本文介绍了问题存储图像矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C#中以矩阵形式存储图像?
我尝试使用指针进行了很多尝试,但是它不安全并且无法正确使用吗?
How can I store the image in matrix form in C#?
I tried a lot using pointer but it is unsafe and not going in correct way?
推荐答案
如果您的图像是单色的,则可以尝试以下操作:
If your image is monochrome you may try something like:
int[,] BitmapToMatrix(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly,
bmp.PixelFormat);
int bytesPerPixel = bmpData.Stride / bmp.Width;
//if you want to access your pixel as matrix[i, j]
//(i = row index, j = column index)
//then allocate your matrix like this:
int[,] matrix = new int[bmp.Height, bmp.Width];
//we will use pointers
unsafe
{
for (int i = 0; i < bmp.Height; i++)
{
byte* p = (byte*)bmpData.Scan0.ToPointer() +
(i * bmp.Height) * bmpData.Stride;
for (int j = 0; j < bmp.Width; j++)
{
//don't bother with color components,
//just extract the first pixel value
byte* pixel = p + j * bytesPerPixel;
matrix[i, j] = (int)*pixel;
}
}
}
bmp.UnlockBits(bmpData);
return matrix;
}
如果您不想使用不安全的代码,则可以看看:
http://msdn.microsoft.com/en-us/library/system. drawing.bitmap.unlockbits.aspx
如果要存储颜色,请尝试以下操作:
If you don''t want to use unsafe code, then you may have a look to:
http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx
If you want to store the colors, then try something like:
Color[,] BitmapToMatrix(Bitmap bmp)
{
//if you want to access your pixel as matrix[i, j]
// (i = row index, j = column index)
//then allocate your matrix like this:
Color[,] matrix = new Color[bmp.Height, bmp.Width];
for (int i = 0; i < bmp.Height; i++)
{
for (int j = 0; j < bmp.Width; j++)
{
//This work for any bitmap format but is very slow
//if you want to be more efficient,
//consider using the first solution.
//But you must then deal with the internal data
//by yourself to extract the color components
matrix[i, j] = bmp.GetPixel(j, i);
}
}
return matrix;
}
这篇关于问题存储图像矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文