gpt4 book ai didi

c# - 如何在 for 循环中创建数组

转载 作者:太空宇宙 更新时间:2023-11-03 19:32:37 24 4
gpt4 key购买 nike

好的,我需要像这样创建两个数组:

        double[][] TrainPatterns = { 
new double[] { 0.0, 0.0 },
new double[] { 0.0, 1.0 },
new double[] { 0.0, 2.0 }
};
double[][] TrainResults = {
new double[] { 0.0 },
new double[] { 1.0 },
new double[] { 1.0 }
};

但是每个有 100 个项目。

我正在从图像中读取数组的值(TrainPatterns 包含像素的 x 和 y 坐标,TrainResults 包含像素的颜色,0 表示黑色,1 表示白色)。

我正在像这样遍历图像:

        Bitmap objBitmap = new Bitmap("im.bmp");
for (int y = 0; y < objBitmap.Height; y++)
{
for (int x = 0; x < objBitmap.Width; x++)
{
// here I need to insert new double[] { (double)x, (double)y } to the
// TrainPatterns array
Color col = objBitmap.GetPixel(x, y);
if (col.R == 255 && col.G == 255 && col.B == 255)
{
// white color
// here I need to insert new double[] { 1.0 } to the
// TrainResults
}
if (col.R == 0 && col.G == 0 && col.B == 0)
{
// black color
// here I need to insert new double[] { 0.0 } to the
// TrainResults
}
}
}

如何在 for 循环中动态地向这些数组添加项目?我知道图像的宽度为 10px,高度为 10px,所以我知道数组的长度均为 100。

最佳答案

你肯定想在开始循环之前分配数组,你会想在完成后使用结果。当像素不是白色或黑色时,您应该做一些有意义的事情。像这样:

        Bitmap objBitmap = new Bitmap("im.bmp");
double[][] array = new double[objBitmap.Height][];
for (int y = 0; y < objBitmap.Height; y++) {
array[y] = new double[objBitmap.Width];
for (int x = 0; x < objBitmap.Width; x++) {
Color col = objBitmap.GetPixel(x, y);
if (col == Color.White) array[y][x] = 1.0;
else if (col == Color.Black) array[y][x] = 0.0;
else array[y][x] = 0.5; // whatever
}
}
// Do something with array
//...

不确定位图的生命周期,您应该在某处调用 objBitmap.Dispose()。利用 using 语句。

关于c# - 如何在 for 循环中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4119786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com