最近项目需要检测图像是否存在偏色、过亮、模糊等缺陷。由于主要用在视频监控上,对性能要求比较高。有几项检测必须要在Lab彩色下进行,而众所周知Rgb => Lab 计算量较大,C#搞得定搞不定?测试表明,用纯C#编写的Rgb => Lab代码在性能上与C编写的Rgb => Lab代码极为接近。
1. Rgb24和Lab24
Rgb是电脑上使用较多的彩色空间,Lab是针对人的感知设计的均匀彩色空间,很多情况下进行彩色图像分析,需要在Rgb彩色空间和Lab彩色空间之间进行转化。关于Lab彩色空间的详细介绍和Rgb空间与Lab空间的转换公式见维基百科的对应词条 Lab色彩空间,本文不再叙述。
使用Rgb24和Lab24两个struct定义Rgb彩色空间的像素和Lab彩色空间的像素。
1 public partial struct Rgb24
2 {
3 public static Rgb24 WHITE = new Rgb24 { Red = 255, Green = 255, Blue = 255 };
4 public static Rgb24 BLACK = new Rgb24();
5 public static Rgb24 RED = new Rgb24 { Red = 255 };
6 public static Rgb24 BLUE = new Rgb24 { Blue = 255 };
7 public static Rgb24 GREEN = new Rgb24 { Green = 255 };
8
9 [FieldOffset(0)]
10 public Byte Blue;
11 [FieldOffset(1)]
12 public Byte Green;
13 [FieldOffset(2)]
14 public Byte Red;
15
16 public Rgb24(int red, int green, int blue)
17 {
18 Red = (byte)red;
19 Green = (byte)green;
20 Blue = (byte)blue;
21 }
22
23 public Rgb24(byte red, byte green, byte blue)
24 {
25 Red = red;
26 Green = green;
27 Blue = blue;
28 }
29 }
30
31 public partial struct Lab24
32 {
33 public byte L;
34 public byte A;
35 public byte B;
36
37 public Lab24(byte l,byte a,byte b)
38 {
39 L = l;
40 A = a;
41 B = b;
42 }
43
44 public Lab24(int l,int a,int b)
45 {
46 L = (byte)l;
47 A = (byte)a;
48 B = (byte)b;
49 }
50 }
2 {
3 public static Rgb24 WHITE = new Rgb24 { Red = 255, Green = 255, Blue = 255 };
4 public static Rgb24 BLACK = new Rgb24();
5 public static Rgb24 RED = new Rgb24 { Red = 255 };
6 public static Rgb24 BLUE = new Rgb24 { Blue = 255 };
7 public static Rgb24 GREEN = new Rgb24 { Green = 255 };
8
9 [FieldOffset(0)]
10 public Byte Blue;
11 [FieldOffset(1)]
12 public Byte Green;
13 [FieldOffset(2)]
14 public Byte Red;
15
16 public Rgb24(int red, int green, int blue)
17 {
18 Red = (byte)red;
19 Green = (byte)green;
20 Blue = (byte)blue;
21 }
22
23 public Rgb24(byte red, byte green, byte blue)
24 {
25 Red = red;
26 Green = green;
27 Blue = blue;
28 }
29 }
30
31 public partial struct Lab24
32 {
33 public byte L;
34 public byte A;
35 public byte B;
36
37 public Lab24(byte l,byte a,byte b)
38 {
39 L = l;
40 A = a;
41 B = b;
42 }
43
44 public Lab24(int l,int a,int b)
45 {
46 L = (byte)l;
47 A = (byte)a;
48 B = (byte)b;
49 }
50 }