http://blog.csdn.net/huangli19870217/article/details/51058780
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <HalconCpp.h>
#include <HalconCDefs.h>
#include <HProto.h>
Hobject IplImageToHImage(cv::Mat& pImage);
cv::Mat HImageToIplImage(Hobject &Hobj);
int _tmain(int argc, _TCHAR* argv[])
{
Hobject Image, GrayImage;
read_image(&Image, "1.jpg");;
rgb1_to_gray(Image, &GrayImage);
cv::Mat opencvImg = HImageToIplImage(GrayImage);
return 0;
}
cv::Mat HImageToIplImage(Hobject &Hobj)
{
cv::Mat pImage;
Hlong htChannels;
char cType[MAX_STRING];
Hlong width, height;
width = height = 0;
//转换图像格式
convert_image_type(Hobj, &Hobj, "byte");
count_channels(Hobj, &htChannels);
if (htChannels == 1)
{
unsigned char *ptr;
get_image_pointer1(Hobj, (Hlong *)&ptr, cType, &width, &height);
pImage = cv::Mat(height, width, CV_8UC1);
memcpy(pImage.data, ptr, width * height);
}
else if (htChannels == 3)
{
unsigned char *ptrRed, *ptrGreen, *ptrBlue;
ptrRed = ptrGreen = ptrBlue = NULL;
get_image_pointer3(Hobj, (Hlong *)&ptrRed, (Hlong *)&ptrGreen, (Hlong *)&ptrBlue, cType, &width, &height);
pImage = cv::Mat(height, width, CV_8UC3);
for (int row = 0; row < height; row++)
{
uchar* ptr = pImage.ptr<uchar>(row);
for (int col = 0; col < width; col++)
{
ptr[3 * col] = ptrBlue[row * width + col];
ptr[3 * col + 1] = ptrGreen[row * width + col];
ptr[3 * col + 2] = ptrRed[row * width + col];
}
}
}
return pImage;
}
Hobject IplImageToHImage(cv::Mat& pImage)
{
Hobject Hobj = NULL;
if (3 == pImage.channels())
{
cv::Mat pImageRed, pImageGreen, pImageBlue;
std::vector<cv::Mat> sbgr(3);
cv::split(pImage, sbgr);
int length = pImage.rows * pImage.cols;
uchar *dataBlue = new uchar[length];
uchar *dataGreen = new uchar[length];
uchar *dataRed = new uchar[length];
int height = pImage.rows;
int width = pImage.cols;
for (int row = 0; row <height; row++)
{
uchar* ptr = pImage.ptr<uchar>(row);
for (int col = 0; col < width; col++)
{
dataBlue[row * width + col] = ptr[3 * col];
dataGreen[row * width + col] = ptr[3 * col + 1];
dataRed[row * width + col] = ptr[3 * col + 2];
}
}
gen_image3(&Hobj, "byte", width, height, (Hlong)(dataRed), (Hlong)(dataGreen), (Hlong)(dataBlue));
delete[] dataRed;
delete[] dataGreen;
delete[] dataBlue;
}
else if (1 == pImage.channels())
{
int height = pImage.rows;
int width = pImage.cols;
uchar *dataGray = new uchar[width * height];
memcpy(dataGray, pImage.data, width * height);
gen_image1(&Hobj, "byte", width, height, (Hlong)(dataGray));
delete[] dataGray;
}
return Hobj;
}