我有这个功能来比较图像比较中的红色,蓝色,绿色和Alpha像素,以便比较两个图像的循环
代码:
var o = 255 - c1.A;
var t = tolerance < o ? o : tolerance;
var b = AreSimiliar(ref c1.B, ref c2.B, ref t);
var g = AreSimiliar(ref c1.G, ref c2.G, ref t);
var r = AreSimiliar(ref c1.R, ref c2.R, ref t);
if (b && g && r) continue;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AreSimiliar(ref byte v1, ref byte v2, ref double tolerance)
{
var z = v1 - v2;
var t = z > 0 ? z : -z;
return t <= tolerance;
}
问题是它使用了如此多的CPU,虽然没有使用外部代码,测试将其缩小到导致负载的代码。
答案 0 :(得分:2)
试试这个
var o = 255 - c1.A;
var t = tolerance < o ? o : tolerance;
if (AreSimiliar(c1.B, c2.B, t) &&
AreSimiliar(c1.G, c2.G, t) &&
AreSimiliar(c1.R, c2.R, t)) continue;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AreSimiliar(byte v1, byte v2, double tolerance)
{
var z = v1 - v2;
var t = z > 0 ? z : -z;
return t <= tolerance;
}
这可能会更好
var o = 255 - c1.A;
var t = tolerance < o ? o : tolerance;
if (Abs(c1.B - c2.B) <= t) & //or &&
Abs(c1.G - c2.G) <= t) & //or &&
Abs(c1.R - c2.R) <= t)) continue;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Abs(int d)
{
int y = (d >> 31);
return (d ^ y) - y;
}
答案 1 :(得分:0)
让您的代码免费分支
使用原生SIMD(avx,sse)代码 https://en.wikipedia.org/wiki/SIMD