C#:声明和使用XNA向量进行矩阵乘法等。人

时间:2011-07-05 02:55:08

标签: c# image-processing matrix-multiplication

我正在尝试在C#中声明并使用XNA向量进行矩阵乘法,求和等。

这些将用于图像处理,使其比常规的SetPixel和GetPixel更快。但是,我总是找不到一个有效的例子,我在网上尝试了很多例子,但似乎我遗漏了一些东西。

任何帮助和示例代码?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果您担心性能,那么您可以在unsafe上下文中恢复编码。

通过使用unsafe关键字标记类型,类型成员或语句块,您可以使用指针类型并对该范围内的内存执行C ++样式指针操作,并且能够在托管执行中执行此操作框架。不安全的代码比相应的安全实现运行得更快。

这是一个很好的简短示例,它来自Nutshell中的C#4.0一书:

unsafe void BlueFilter (int[,] bitmap)
  {
    int length = bitmap.Length;
    fixed (int* b=bitmap)
    {
        int* p=b;
        for (int i=0, i<length; i++)
        *p++ &= 0xFF;
    }
   }

Source


除此之外,你还应该看看这个SO问题

Why is matrix multiplication in .NET so slow?

答案 1 :(得分:0)

向量只是1 x n矩阵。创建一个Matrix类,其中包含求和和乘法的方法。

public class Matrix
{
    private int[,] m_array;

    public Matrix(int m, int n)
    {
        m_array = new int[m, n];
    }

    public Matrix(int[,] other)
    {
        m_array = other;
    }

    public Matrix Mult(Matrix other)
    {
        if (this.m_array.GetLength(1) != other.m_array.GetLength(0))
            return null;

        int[,] res = new int[this.m_array.GetLength(0), other.m_array.GetLength(1)];

        for (int i = 0; i < this.m_array.GetLength(0); ++i)
            for (int j = 0; j < other.m_array.GetLength(1); ++j)
            {
                int s = 0;
                for (int k = 0; k < this.m_array.GetLength(1); ++k)
                    s += this.m_array[i, k] * other.m_array[k, j];
                res[i, j] = s;
            }

        return new Matrix(res);
    }
}