OpenCV和Halcon之间有很多数据要转换,特此记录
1 字符串与HTuple互转
1 char *pImageName = "D:/data/temp.png";
2 HTuple hv_path;
3 hv_path = (HTuple)(pImageName);
4 cout << hv_path.S() << endl;
5 string path = hv_path.S();
6 cout << path<<endl;
2 double与HTuple互转
1 HTuple hv_data;
2 hv_data = 10.0;
3 double data = hv_path.D();
4 cout << data<<endl;
3 Mat 与 HObject互转,这两个项目经常用,代码来自别的博客,非常感谢。
Mat 转 HObject
1 HObject Cpu_halcon_detect::mat_to_hobject(Mat& image)
2 {
3 HObject Hobj = HObject();
4 int hgt = image.rows;
5 int wid = image.cols;
6 int i;
7 // CV_8UC3
8 if (image.type() == CV_8UC3)
9 {
10 vector<Mat> imgchannel;
11 split(image, imgchannel);
12 Mat imgB = imgchannel[0];
13 Mat imgG = imgchannel[1];
14 Mat imgR = imgchannel[2];
15 uchar* dataR = new uchar[hgt*wid];
16 uchar* dataG = new uchar[hgt*wid];
17 uchar* dataB = new uchar[hgt*wid];
18 for (i = 0; i < hgt; i++)
19 {
20 memcpy(dataR + wid*i, imgR.data + imgR.step*i, wid);
21 memcpy(dataG + wid*i, imgG.data + imgG.step*i, wid);
22 memcpy(dataB + wid*i, imgB.data + imgB.step*i, wid);
23 }
24 GenImage3(&Hobj, "byte", wid, hgt, (Hlong)dataR, (Hlong)dataG, (Hlong)dataB);
25 delete[]dataR;
26 delete[]dataG;
27 delete[]dataB;
28 dataR = NULL;
29 dataG = NULL;
30 dataB = NULL;
31 }
32 // CV_8UCU1
33 else if (image.type() == CV_8UC1)
34 {
35 uchar* data = new uchar[hgt*wid];
36 for (i = 0; i < hgt; i++)
37 memcpy(data + wid*i, image.data + image.step*i, wid);
38 GenImage1(&Hobj, "byte", wid, hgt, (Hlong)data);
39 delete[] data;
40 data = NULL;
41 }
42 return Hobj;
43 }
HObject 转 Mat
1 Mat Cpu_halcon_detect::hobject_to_mat(HObject Hobj)
2 {
3 HTuple htCh = HTuple();
4 HTuple cType;
5 Mat Image;
6 ConvertImageType(Hobj, &Hobj, "byte");
7 CountChannels(Hobj, &htCh);
8 HTuple wid;
9 HTuple hgt;
10 int W, H;
11 if (htCh[0].I() == 1)
12 {
13 HTuple ptr;
14 GetImagePointer1(Hobj, &ptr, &cType, &wid, &hgt);
15 W = (Hlong)wid;
16 H = (Hlong)hgt;
17 Image.create(H, W, CV_8UC1);
18 uchar* pdata = (uchar*)ptr[0].I();
19 memcpy(Image.data, pdata, W*H);
20 }
21 else if (htCh[0].I() == 3)
22 {
23 HTuple ptrR, ptrG, ptrB;
24 GetImagePointer3(Hobj, &ptrR, &ptrG, &ptrB, &cType, &wid, &hgt);
25 W = (Hlong)wid;
26 H = (Hlong)hgt;
27 Image.create(H, W, CV_8UC3);
28 vector<Mat> vecM(3);
29 vecM[2].create(H, W, CV_8UC1);
30 vecM[1].create(H, W, CV_8UC1);
31 vecM[0].create(H, W, CV_8UC1);
32 uchar* pr = (uchar*)ptrR[0].I();
33 uchar* pg = (uchar*)ptrG[0].I();
34 uchar* pb = (uchar*)ptrB[0].I();
35 memcpy(vecM[2].data, pr, W*H);
36 memcpy(vecM[1].data, pg, W*H);
37 memcpy(vecM[0].data, pb, W*H);
38 merge(vecM, Image);
39 }
40 return Image;
41 }