我希望将以下 Python(Numpy 和 Scipy)代码转换为 C#。 IronPython 不适用于我的情况。 这里的代码用于图像处理程序,并且对表示灰度图像的多维浮点数组进行操作。它正在查找行和列之间的累积差异,然后检查差异的第 5 个和第 95 个百分位,以便能够裁剪到该差异。
lower_percentile=5, upper_percentile=95
# row-wise differences
rw = np.cumsum(np.sum(np.abs(np.diff(image, axis=1)), axis=1))
# column-wise differences
cw = np.cumsum(np.sum(np.abs(np.diff(image, axis=0)), axis=0))
# compute percentiles
upper_column_limit = np.searchsorted(cw, np.percentile(cw, upper_percentile), side='left')
lower_column_limit = np.searchsorted(cw, np.percentile(cw, lower_percentile), side='right')
upper_row_limit = np.searchsorted(rw, np.percentile(rw, upper_percentile), side='left')
lower_row_limit = np.searchsorted(rw, np.percentile(rw, lower_percentile), side='right')
到目前为止,我拥有的是一些用于获取多维数组的 C# 代码,并且我还研究了其他解决方案。 此解决方案处理 np.diff 操作,但仅适用于一维数组。我还研究了使用嵌套循环对 2D 数组进行操作的解决方案,例如 this one。我知道我可能需要结合这些方法,但我不确定如何结合。
最终,这里的目标是在继续处理多维数组之前对其进行某种程度的智能裁剪。看起来一旦定义了数组的重要区域,就可以使用 this 来进行裁剪。我绝对愿意接受其他方式到达那里。我目前有以下 C# 代码,它返回多维数组:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
namespace ImageTest
{
class Program
{
static void Main(string[] args)
{
Bitmap img;
WebClient client = new WebClient();
byte[] b = client.DownloadData("https://pixabay.com/static/uploads/photo/2012/11/28/08/56/mona-lisa-67506_960_720.jpg");
using (MemoryStream stream = new MemoryStream(b))
{
img = new Bitmap(Image.FromStream(stream));
}
img = MakeGrayscale(img);
var imgArray = FromGrayscaleToDoubles(img);
//THE CROP NEEDS TO HAPPEN HERE
}
public static Bitmap MakeGrayscale(Bitmap original)
{
//create a blank bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
//get a graphics object from the new image
Graphics g = Graphics.FromImage(newBitmap);
//create the grayscale ColorMatrix
ColorMatrix colorMatrix = new ColorMatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
//create some image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color matrix attribute
attributes.SetColorMatrix(colorMatrix);
//draw the original image on the new image
//using the grayscale color matrix
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
//dispose the Graphics object
g.Dispose();
return newBitmap;
}
public static double[,] FromGrayscaleToDoubles(Bitmap bitmap)
{
var result = new double[bitmap.Width, bitmap.Height];
for (int x = 0; x < bitmap.Width; x++)
for (int y = 0; y < bitmap.Height; y++)
result[x, y] = (double)bitmap.GetPixel(x, y).R / 255;
return result;
}
}
}
对于迟到的人来说,我最终使用 Image Magick 来处理裁剪。最终,数组问题在 C# 世界中并不容易解决。