[C#] Bgr24彩色位图转为Gray8灰度位图的跨平台SIMD硬件加速向量算法
将彩色位图转为灰度位图,是图像处理的常用算法。本文将介绍 Bgr24彩色位图转为Gray8灰度位图的算法,除了会给出标量算法外,还会给出向量算法。且这些算法是跨平台的,同一份源代码,能在 X86及Arm架构上运行,且均享有SIMD硬件加速。一、标量算法
1.1 算法实现
对于彩色转灰度,由于人眼对红绿蓝三种颜色的敏感程度不同,在灰度转换时,每个颜色分配的权重也是不同的。有一个很著名的心理学公式:
Gray = R*0.299 + G*0.587 + B*0.114
该公式含有浮点数,而浮点数运算一般比较慢。
于是在具体实现时,需要做一定优化。可以将小数转为定点整数,这样便能将除法转为移位。整数计算比浮点型快,移位运算和加减法比乘除法快,于是取得了比较好的效果。
但是这种方法也会带来一定的精度损失,我们可以根据实际情况选择定点整数的精度位数。
这里我们使用16位精度,源代码如下。
public static unsafe void ScalarDo(BitmapData src, BitmapData dst) {
const int cbPixel = 3; // Bgr24
const int shiftPoint = 16;
const int mulPoint = 1 << shiftPoint; // 0x10000
const int mulRed = (int)(0.299 * mulPoint + 0.5); // 19595
const int mulGreen = (int)(0.587 * mulPoint + 0.5); // 38470
const int mulBlue = mulPoint - mulRed - mulGreen; // 7471
int width = src.Width;
int height = src.Height;
int strideSrc = src.Stride;
int strideDst = dst.Stride;
byte* pRow = (byte*)src.Scan0.ToPointer();
byte* qRow = (byte*)dst.Scan0.ToPointer();
for (int i = 0; i < height; i++) {
byte* p = pRow;
byte* q = qRow;
for (int j = 0; j < width; j++) {
*q = (byte)((p * mulRed + p * mulGreen + p * mulBlue) >> shiftPoint);
p += cbPixel; // Bgr24
q += 1; // Gray8
}
pRow += strideSrc;
qRow += strideDst;
}
}1.2 基准测试代码
使用 BenchmarkDotNet 进行基准测试。
可以实现分配好数据。源代码如下。
private static readonly Random _random = new Random(1);
private BitmapData _sourceBitmapData = null;
private BitmapData _destinationBitmapData = null;
private BitmapData _expectedBitmapData = null;
public int Width { get; set; }
public int Height { get; set; }
~Bgr24ToGrayBgr24Benchmark() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
if (_disposed) return;
_disposed = true;
if (disposing) {
Cleanup();
}
}
private BitmapData AllocBitmapData(int width, int height, PixelFormat format) {
const int strideAlign = 4;
if (width <= 0) throw new ArgumentOutOfRangeException($"The width({width}) need > 0!");
if (height <= 0) throw new ArgumentOutOfRangeException($"The width({height}) need > 0!");
int stride = 0;
switch (format) {
case PixelFormat.Format8bppIndexed:
stride = width * 1;
break;
case PixelFormat.Format24bppRgb:
stride = width * 3;
break;
}
if (stride <= 0) throw new ArgumentOutOfRangeException($"Invalid pixel format({format})!");
if (0 != (stride % strideAlign)) {
stride = stride - (stride % strideAlign) + strideAlign;
}
BitmapData bitmapData = new BitmapData();
bitmapData.Width = width;
bitmapData.Height = height;
bitmapData.PixelFormat = format;
bitmapData.Stride = stride;
bitmapData.Scan0 = Marshal.AllocHGlobal(stride * height);
return bitmapData;
}
private void FreeBitmapData(BitmapData bitmapData) {
if (null == bitmapData) return;
if (IntPtr.Zero == bitmapData.Scan0) return;
Marshal.FreeHGlobal(bitmapData.Scan0);
bitmapData.Scan0 = IntPtr.Zero;
}
public void Cleanup() {
FreeBitmapData(_sourceBitmapData); _sourceBitmapData = null;
FreeBitmapData(_destinationBitmapData); _destinationBitmapData = null;
FreeBitmapData(_expectedBitmapData); _expectedBitmapData = null;
}
public void Setup() {
Height = Width;
// Create.
Cleanup();
_sourceBitmapData = AllocBitmapData(Width, Height, PixelFormat.Format24bppRgb);
_destinationBitmapData = AllocBitmapData(Width, Height, PixelFormat.Format8bppIndexed);
_expectedBitmapData = AllocBitmapData(Width, Height, PixelFormat.Format8bppIndexed);
RandomFillBitmapData(_sourceBitmapData, _random);
}上面源代码中的“Vectors.ShiftRightLogical_Const”,是VectorTraits 库提供的方法。它能替代NET 7.0 新增的 Vector.ShiftRightLogical 方法,使早期版本的 NET 也能使用逻辑右移位。
“Vectors.Multiply”也是VectorTraits 库提供的方法。它能避免无符号类型有时没有硬件加速的问题。
2.3 基准测试代码
public void Scalar() {
ScalarDo(_sourceBitmapData, _destinationBitmapData);
}完整源码在 Bgr24ToGray8Benchmark.cs
随后为该算法编写基准测试代码。
三、基准测试结果
3.1 X86 架构
X86架构下的基准测试结果如下。
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_X_Part0 = Vector128.Create((sbyte)0, 3, 6, 9, 12, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_X_Part1 = Vector128.Create((sbyte)-1, -1, -1, -1, -1, -1, 2, 5, 8, 11, 14, -1, -1, -1, -1, -1).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_X_Part2 = Vector128.Create((sbyte)-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 4, 7, 10, 13).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_Y_Part0 = Vector128.Create((sbyte)1, 4, 7, 10, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_Y_Part1 = Vector128.Create((sbyte)-1, -1, -1, -1, -1, 0, 3, 6, 9, 12, 15, -1, -1, -1, -1, -1).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_Y_Part2 = Vector128.Create((sbyte)-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 5, 8, 11, 14).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_Z_Part0 = Vector128.Create((sbyte)2, 5, 8, 11, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_Z_Part1 = Vector128.Create((sbyte)-1, -1, -1, -1, -1, 1, 4, 7, 10, 13, -1, -1, -1, -1, -1, -1).AsByte();
static readonly Vector128<byte> YGroup3Unzip_Shuffle_Byte_Z_Part2 = Vector128.Create((sbyte)-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 3, 6, 9, 12, 15).AsByte();
public static Vector128<byte> YGroup3Unzip(Vector128<byte> data0, Vector128<byte> data1, Vector128<byte> data2, out Vector128<byte> y, out Vector128<byte> z) {
var f0A = YGroup3Unzip_Shuffle_Byte_X_Part0;
var f0B = YGroup3Unzip_Shuffle_Byte_X_Part1;
var f0C = YGroup3Unzip_Shuffle_Byte_X_Part2;
var f1A = YGroup3Unzip_Shuffle_Byte_Y_Part0;
var f1B = YGroup3Unzip_Shuffle_Byte_Y_Part1;
var f1C = YGroup3Unzip_Shuffle_Byte_Y_Part2;
var f2A = YGroup3Unzip_Shuffle_Byte_Z_Part0;
var f2B = YGroup3Unzip_Shuffle_Byte_Z_Part1;
var f2C = YGroup3Unzip_Shuffle_Byte_Z_Part2;
var rt0 = Sse2.Or(Sse2.Or(Ssse3.Shuffle(data0, f0A), Ssse3.Shuffle(data1, f0B)), Ssse3.Shuffle(data2, f0C));
var rt1 = Sse2.Or(Sse2.Or(Ssse3.Shuffle(data0, f1A), Ssse3.Shuffle(data1, f1B)), Ssse3.Shuffle(data2, f1C));
var rt2 = Sse2.Or(Sse2.Or(Ssse3.Shuffle(data0, f2A), Ssse3.Shuffle(data1, f2B)), Ssse3.Shuffle(data2, f2C));
y = rt1;
z = rt2;
return rt0;
}
[*]Scalar: 标量算法。
[*]UseVectors: 矢量算法。
[*]UseVectorsParallel: 并发的矢量算法。
3.2 Arm 架构
同样的源代码可以在 Arm 架构上运行。基准测试结果如下。
public static unsafe void UseVectorsDoBatch(byte* pSrc, int strideSrc, int width, int height, byte* pDst, int strideDst) {
const int cbPixel = 3; // Bgr24
const int shiftPoint = 8;
const int mulPoint = 1 << shiftPoint; // 0x100
const ushort mulRed = (ushort)(0.299 * mulPoint + 0.5); // 77
const ushort mulGreen = (ushort)(0.587 * mulPoint + 0.5); // 150
const ushort mulBlue = mulPoint - mulRed - mulGreen; // 29
Vector<ushort> vmulRed = new Vector<ushort>(mulRed);
Vector<ushort> vmulGreen = new Vector<ushort>(mulGreen);
Vector<ushort> vmulBlue = new Vector<ushort>(mulBlue);
int vectorWidth = Vector<byte>.Count;
int maxX = width - vectorWidth;
byte* pRow = pSrc;
byte* qRow = pDst;
for (int i = 0; i < height; i++) {
Vector<byte>* pLast = (Vector<byte>*)(pRow + maxX * cbPixel);
Vector<byte>* qLast = (Vector<byte>*)(qRow + maxX * 1);
Vector<byte>* p = (Vector<byte>*)pRow;
Vector<byte>* q = (Vector<byte>*)qRow;
for (; ; ) {
Vector<byte> r, g, b, gray;
Vector<ushort> wr0, wr1, wg0, wg1, wb0, wb1;
// Load.
b = Vectors.YGroup3Unzip(p, p, p, out g, out r);
// widen(r) * mulRed + widen(g) * mulGreen + widen(b) * mulBlue
Vector.Widen(r, out wr0, out wr1);
Vector.Widen(g, out wg0, out wg1);
Vector.Widen(b, out wb0, out wb1);
wr0 = Vectors.Multiply(wr0, vmulRed);
wr1 = Vectors.Multiply(wr1, vmulRed);
wg0 = Vectors.Multiply(wg0, vmulGreen);
wg1 = Vectors.Multiply(wg1, vmulGreen);
wb0 = Vectors.Multiply(wb0, vmulBlue);
wb1 = Vectors.Multiply(wb1, vmulBlue);
wr0 = Vector.Add(wr0, wg0);
wr1 = Vector.Add(wr1, wg1);
wr0 = Vector.Add(wr0, wb0);
wr1 = Vector.Add(wr1, wb1);
// Shift right and narrow.
wr0 = Vectors.ShiftRightLogical_Const(wr0, shiftPoint);
wr1 = Vectors.ShiftRightLogical_Const(wr1, shiftPoint);
gray = Vector.Narrow(wr0, wr1);
// Store.
*q = gray;
// Next.
if (p >= pLast) break;
p += cbPixel;
++q;
if (p > pLast) p = pLast; // The last block is also use vector.
if (q > qLast) q = qLast;
}
pRow += strideSrc;
qRow += strideDst;
}
}附录
[*]完整源代码: https://github.com/zyl910/VectorTraits.Sample.Benchmarks/blob/main/VectorTraits.Sample.Benchmarks.Inc/Image/Bgr24ToGray8Benchmark.cs
[*]YGroup3Unzip 的文档: https://zyl910.github.io/VectorTraits_doc/api/Zyl.VectorTraits.Vectors.YGroup3Unzip.html
[*]VectorTraits 的NuGet包: https://www.nuget.org/packages/VectorTraits
[*]VectorTraits 的在线文档: https://zyl910.github.io/VectorTraits_doc/
[*]VectorTraits 源代码: https://github.com/zyl910/VectorTraits
出处:http://www.cnblogs.com/zyl910/ 版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0.
来源:https://www.cnblogs.com/zyl910/p/18555805/VectorTraits_Sample_Image_Bgr24ToGray8Benchmark
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]