【问题标题】:C#: Declaring and Using XNA Vectors for Matrix Multiplication, et. alC#:声明和使用 XNA 向量进行矩阵乘法等。人
【发布时间】:2011-09-28 11:43:59
【问题描述】:

我正在尝试在 C# 中为矩阵乘法、求和等声明和使用 XNA 向量。

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

任何帮助和示例代码?

谢谢!

【问题讨论】:

  • 我不是 100% 确定,但应该有一个可以使用的内置 Matrix 类。
  • 我正在努力促进 GPU 获得更快的图像处理能力。

标签: c# image-processing matrix-multiplication


【解决方案1】:

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

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

这是一个不错的简短示例,来自《C# 4.0 in a Nutshell》一书:

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 Question

Why is matrix multiplication in .NET so slow?

【讨论】:

  • 谢谢。但是如何利用 GPU 呢?
  • @johnshaddad |您不能直接使用 GPU,因为他们的供应商不提供托管 API,而且他们也没有基于 x86/x64 的指令集,NVIDIA 提供了 CUDA,但它只支持 C++。所以虽然你可以构建一个互操作层,但使用并行会更简单:)
  • 哎呀哈哈但是实时处理高清图像呢?就像在我想实时处理的高清视频中一样(例如翻转照片或做其他事情)?任何指向什么最适合这种情况的指针,可能带有教程或示例代码?谢谢
【解决方案2】:

Verctors 只是 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);
    }
}

【讨论】:

  • 谢谢。但是如何利用 GPU 呢?
猜你喜欢
  • 2020-10-25
  • 2016-02-22
  • 2012-05-30
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
相关资源
最近更新 更多