其他分享
首页 > 其他分享> > 【转载】Halcon中的HObject类型转OpenCV中的Mat类型

【转载】Halcon中的HObject类型转OpenCV中的Mat类型

作者:互联网

HObject→Mat

Mat HObject2Mat(HObject Hobj)
{ 
    HTuple htCh;
    HString cType;
    cv::Mat Image;
    ConvertImageType(Hobj, &Hobj, "byte");
    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<unsigned char *>(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);
        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 *R2 = (unsigned char *)Rptr;
        unsigned char *G = (unsigned char *)Gptr;
        unsigned char *B = (unsigned char *)Bptr;
        memcpy(VecM[2].data, R2, 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 Hobj = HObject();
    int hgt = image.rows;
    int wid = image.cols;
    int i;
    //  CV_8UC3    
    if (image.type() == CV_8UC3)
    {
        vector<cv::Mat> 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;
}

【转载】https://blog.csdn.net/qq_38815760/article/details/88759919

标签:wid,Mat,int,hgt,VecM,Halcon,OpenCV,Hobj
来源: https://www.cnblogs.com/xixixing/p/12598191.html