C# 如何将位图RGB颜色正确转换为2d双数组?
我需要将C# 如何将位图RGB颜色正确转换为2d双数组?,c#,image-processing,bitmap,C#,Image Processing,Bitmap,我需要将位图图像转换为2D双数组。 我希望每个像素都有一个任意的数字,表示在0-1之间缩放的RBG颜色。 我想将位图图像转换为2D双数组,以便对该位图图像应用卷积运算。 因此,我编写了以下代码: public partial class Form1 : Form { public Form1() { InitializeComponent(); Bitmap image = (Bitmap)Bitmap.FromFile("lena.jpg");
位图
图像转换为2D双
数组。我希望每个像素都有一个任意的数字,表示在0-1之间缩放的RBG颜色。 我想将位图图像转换为2D双数组,以便对该位图图像应用卷积运算。 因此,我编写了以下代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Bitmap image = (Bitmap)Bitmap.FromFile("lena.jpg");
pictureBox1.Image = image;
dataGridView1.DataSource = ToDataTable(ToDouble2d(image));
}
public static double[,] ToDouble2d(Bitmap input)
{
int width = input.Width;
int height = input.Height;
double[,] array2d = new double[width, height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color clr = input.GetPixel(x, y);
double iClr = (double)clr.ToArgb();
array2d[x, y] = iClr / 255.0;
}
}
return array2d;
}
public static DataTable ToDataTable(double[,] numbers)
{
DataTable dt = new DataTable();
for (int i = 0; i < numbers.GetLength(1); i++)
{
dt.Columns.Add("Column" + (i + 1));
}
for (var i = 0; i < numbers.GetLength(0); ++i)
{
DataRow row = dt.NewRow();
for (var j = 0; j < numbers.GetLength(1); ++j)
{
row[j] = numbers[i, j];
}
dt.Rows.Add(row);
}
return dt;
}
}
现在,所有强度都变成了-无穷大
那么,处理这种情况的正确方法是什么
注意。此时性能不是问题(例如位图锁定等)。我只是想知道为什么我的代码不能正常工作,以及如何正确地工作。我不知道您想做什么,或者为什么。但是,如果您只需要一个表示RBG值的任意数字,则可以从0缩放到1。你也许可以做这样的事
public static Uint RGBtoUInt(int r, int g, int b)
{
return (uint)(( r << 0 ) | ( g << 8 ) | ( b << 16 ));
}
...
var myArbitaryValue = RGBtoInt(r,g,b) / (double)16581375; // maximum 24bit color value
公共静态单元RGBtoUInt(int r、int g、int b)
{
return(uint)((r好的,我已经从中解决了这个问题
publicstaticdouble[,]ToDouble2d(位图输入)
{
int width=input.width;
int高度=输入高度;
double[,]array2d=新的double[宽度,高度];
对于(int y=0;y
因此,您想获得颜色的色调饱和度亮度(HSL)亮度值吗?只需RGB或alpha通道ToArgb()是正常的
给出负值;UInt32
以alpha值开始,通常为0xFF,但由于它被表示为Int32
,这意味着第一位被启用,因此数字被视为负值。要解决这个问题,只需先将其转换为UInt32
。好吧,你的问题甚至没有提到你您想将其视为灰度。您也可以使用颜色中的GetBrightness()
值。
public static Uint RGBtoUInt(int r, int g, int b)
{
return (uint)(( r << 0 ) | ( g << 8 ) | ( b << 16 ));
}
...
var myArbitaryValue = RGBtoInt(r,g,b) / (double)16581375; // maximum 24bit color value
public static double[,] ToDouble2d(Bitmap input)
{
int width = input.Width;
int height = input.Height;
double[,] array2d = new double[width, height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color cl = input.GetPixel(x, y);
// A 2d double data is always Grayscale.
// So, three elements are averaged.
double gray = ((cl.R * 0.3) + (cl.G * 0.59) + (cl.B * 0.11));
array2d[x, y] = gray/255.0;
}
}
return array2d;
}