一、对比实验及结论
是HImage的构造函数:public HImage(HObject hObject);
不是网上大部分文章所写的先拿到HObject的图像指针在生成HImage的写法。效率对比如下:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//方法1:使用构造函数
HImage hImage3 = null;
for (int i = 0; i < 100; i++)
{
hImage3 = new HImage(grayImg);
}
Console.WriteLine(stopwatch.ElapsedMilliseconds);
hImage3.WriteImage("bmp", 0, "E://3");
stopwatch.Restart();
//方法2:先获取HObject图像指针,然后生成图像
HImage image4 = null;
for (int i = 0; i < 100; i++)
{
image4 = new HImage();
HobjectToHimage(grayImg, ref image4);
}
Console.WriteLine(stopwatch.ElapsedMilliseconds);
image4.WriteImage("bmp", 0, "E://4");
//函数原型
static void HobjectToHimage(HObject hobject, ref HImage image)
{
HTuple pointer, type, width, height;
HOperatorSet.GetImagePointer1(hobject, out pointer, out type, out width, out height);
image.GenImage1(type, width, height, pointer);
}
//转换彩色图像的方法
static void HobjectToRGBHimage(HObject hobject, ref HImage image)
{
HTuple pointerRed, pointerGreen, pointerBlue, type, width, height;
HOperatorSet.GetImagePointer3(hobject, out pointerRed, out pointerGreen, out pointerBlue, out type, out width, out height);
image.GenImage3(type, width, height, pointerRed, pointerGreen, pointerBlue);
}
结果如下:
二、原因分析
使用构造函数的方法没拷贝图像数据,只是进行了类型检查而已;而另一种方法进行了图像数据的拷贝,自然会很慢。
三、HObject的对象为什么不能强转为HImage?
我们都知道指向子类的基类对象是可以直接强转为子类的,如下面所示:
class A
{
public string Name { get; set; }
}
class B : A
{
public int Id { get; set; } = 5;
}
A a = new B();
A aa = new A();
B b = a as B;
B bb = aa as B;
Console.WriteLine(b?.Id); //5
Console.WriteLine(bb?.Id); //未输出,bb为null
HImage虽然继承于HObject,由以上类比可知,我们得到的HObject其实并未指向HImage的子类,所以不能强转。