本文主要是介绍Hobject 与 Mat 图像数据类型转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 一、halcon和opencv的混合使用
- 二、Mat 转 Hobject
- 三、Hobject 转 Mat
- 总结
一、halcon和opencv的混合使用
图像处理部分获取的图像结构是opencv的mat格式,中间部分处理用到了halcon。需要进行mat和hObject格式的相互转化,使用memcpy可加快转化效率, halcon是linux版本。
二、Mat 转 Hobject
代码如下:
//Mat转Hobject的格式
bool Mat2HObject(cv::Mat &cv_image, HalconCpp::HObject &h_image)
{//1. empty checkif (cv_image.empty()) {LOGE(LOG_TAG, "error Mat2 HObject is empty");return false;}//2. 三通道if (cv_image.channels() == 3) {std::vector<cv::Mat> BgrVector(3);cv::split(cv_image, BgrVector);size_t size = static_cast<size_t>(cv_image.rows * cv_image.cols);uchar *BlueData = new uchar[size];uchar *GreenData = new uchar[size];uchar *RedData = new uchar[size];sleepMs(2);memcpy(BlueData, BgrVector[0].data, size);memcpy(GreenData, BgrVector[1].data, size);memcpy(RedData, BgrVector[2].data, size);HalconCpp::GenImage3(&h_image,"byte",cv_image.cols,cv_image.rows,reinterpret_cast<Hlong>(RedData),reinterpret_cast<Hlong>(GreenData),reinterpret_cast<Hlong>(BlueData));delete [] RedData;delete [] GreenData;delete [] BlueData;} else if (cv_image.channels() == 1) {uchar *GrayData = new uchar[static_cast<size_t>(cv_image.rows * cv_image.cols)];memcpy(GrayData, cv_image.data, static_cast<size_t>(cv_image.rows * cv_image.cols));HalconCpp::GenImage1(&h_image, "byte", cv_image.cols, cv_image.rows, reinterpret_cast<Hlong>(GrayData));delete [] GrayData;}return true;
}
三、Hobject 转 Mat
代码如下:
//Hobject转Mat的格式
bool HObject2MatImg(HalconCpp::HObject& Hobj, cv::Mat& matImg)
{ HalconCpp::HTuple htCh;HalconCpp::HString cType;HalconCpp::ConvertImageType(Hobj, &Hobj, "byte");HalconCpp::CountChannels(Hobj, &htCh);Hlong wid = 0;Hlong hgt = 0;if (htCh[0].I() == 1){HalconCpp::HImage hImg(Hobj);void *ptr = hImg.GetImagePointer1(&cType, &wid, &hgt);int W = wid;int H = hgt;matImg = cv::Mat::zeros(H, W, CV_8UC1);unsigned char *pdata = static_cast<unsigned char *>(ptr);memcpy(matImg.data, pdata, W*H);}else if (htCh[0].I() == 3){void *Rptr;void *Gptr;void *Bptr;HalconCpp::HImage hImg(Hobj);hImg.GetImagePointer3(&Rptr, &Gptr, &Bptr, &cType, &wid, &hgt);int W = wid;int H = hgt;matImg = cv::Mat::zeros(H, W, CV_8UC3);std::vector<cv::Mat> 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, matImg);}return true;
}
总结
opecnv和halcon格式之间的相互转化, 主体仍然使用opencv, halcon处理完成后数据转换成mat格式, 转化效率五百万分辨率的image在i7-8700处理器是不到一个ms。
这篇关于Hobject 与 Mat 图像数据类型转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!