【Halcon】【OpenCV】【C++】HObject与Mat互转函数 (HImage HRegion)

在Halcon与cvMat的联合开发中,可能会涉及到两种图片对象的互相转换情况,由于官方并未提供互转函数,所以需要我们自行编写互转函数,函数如下:

HObject转为Mat函数

cv::Mat HObject2Mat(HObject Hobj)

cv::Mat PingNeiLibrary::HObject2Mat(HObject Hobj)
{
	HTuple htCh;
	HString cType;
	HString strvalue;
	cv::Mat Image;
	HTuple cType2[16] = {0};
	try
	{
		//如果获取image信息失败,说明图像是区域
		GetImageType(Hobj, cType2);
	}
	catch (HException& except)
	{
		//获取原图像大小
		Hlong w = 0;
		Hlong h = 0;
		HImage temp(ho_Image);
		temp.GetImagePointer1(&cType, &w, &h);
		//区域转为图像
		RegionToBin(Hobj, &Hobj, 255, 0, w, h);
		GetImageType(Hobj, cType2);
	}
	try
	{
		strvalue = cType2[0].S();
	}
	catch (HException& except)
	{
		return Image;
	}
	ConvertImageType(Hobj, &Hobj, strvalue);
	CountChannels(Hobj, &htCh);
	Hlong wid = 0;
	Hlong hgt = 0;
	if (htCh[0].I() == 1)
	{
		HImage hImg(Hobj);
		void* ptr = hImg.GetImagePointer1(&cType, &wid, &hgt);//GetImagePointer1(Hobj, &ptr, &cType, &wid, &hgt);
		int W = wid;
		int H = hgt;
		Image.create(H, W, CV_8UC1);
		unsigned char* pdata = static_cast(ptr);
		memcpy(Image.data, pdata, W * H);
	}
	else if (htCh[0].I() == 3)
	{
		void* Rptr;
		void* Gptr;
		void* Bptr;
		HImage hImg(Hobj);
		hImg.GetImagePointer3(&Rptr, &Gptr, &Bptr, &cType, &wid, &hgt);
		int W = wid;
		int H = hgt;
		Image.create(H, W, CV_8UC3);
		std::vector VecM(3);
		VecM[0].create(H, W, CV_8UC1);
		VecM[1].create(H, W, CV_8UC1);
		VecM[2].create(H, W, CV_8UC1);
		unsigned char* R = (unsigned char*)Rptr;
		unsigned char* G = (unsigned char*)Gptr;
		unsigned char* B = (unsigned char*)Bptr;
		memcpy(VecM[2].data, R, W * H);
		memcpy(VecM[1].data, G, W * H);
		memcpy(VecM[0].data, B, W * H);
		cv::merge(VecM, Image);
	}
	return Image;
}

Mat转为HObject函数

HObject Mat2HObject(const cv::Mat& image)

HObject PingNeiLibrary::Mat2HObject(const cv::Mat& image)
{
	HObject Hobj = HObject();
	int hgt = image.rows;
	int wid = image.cols;
	int i;
	//  CV_8UC3  
	if (image.type() == CV_8UC3)
	{
		std::vector imgchannel;
		split(image, imgchannel);
		cv::Mat imgB = imgchannel[0];
		cv::Mat imgG = imgchannel[1];
		cv::Mat imgR = imgchannel[2];
		uchar* dataR = new uchar[hgt * wid];
		uchar* dataG = new uchar[hgt * wid];
		uchar* dataB = new uchar[hgt * wid];
		for (i = 0; i < hgt; i++)
		{
			memcpy(dataR + wid * i, imgR.data + imgR.step * i, wid);
			memcpy(dataG + wid * i, imgG.data + imgG.step * i, wid);
			memcpy(dataB + wid * i, imgB.data + imgB.step * i, wid);
		}
		GenImage3(&Hobj, "byte", wid, hgt, (Hlong)dataR, (Hlong)dataG, (Hlong)dataB);
		delete[]dataR;
		delete[]dataG;
		delete[]dataB;
		dataR = NULL;
		dataG = NULL;
		dataB = NULL;
	}
	//  CV_8UCU1  
	else if (image.type() == CV_8UC1)
	{
		uchar* data = new uchar[hgt * wid];
		for (i = 0; i < hgt; i++)
			memcpy(data + wid * i, image.data + image.step * i, wid);
		GenImage1(&Hobj, "byte", wid, hgt, (Hlong)data);
		delete[] data;
		data = NULL;
	}
	return Hobj;
}
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注