图片类型转换
opencv转QImage
QImage matToQImage(cv::Mat& inMat) {
switch (inMat.type()) {
case CV_8UC1: {
// 8位单通道灰度图
QImage image(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_Grayscale8);
return image;
}
case CV_8UC3: {
// 8位3通道彩色图
QImage image(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_RGB888);
// 由于OpenCV使用BGR格式,需要转换为RGB
image = image.rgbSwapped();
return image;
}
case CV_8UC4: {
// 8位4通道彩色图(BGRA)
QImage image(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_RGBA8888);
return image;
}
default:
// 未知类型,返回空QImage
return QImage();
}
}
opencv转halcon
HalconCpp::HObject MatToHImage(cv::Mat& cv_img)
{
HalconCpp::HObject H_img;
if (cv_img.channels() == 1)
{
int height = cv_img.rows, width = cv_img.cols;
int size = height * width;
uchar* temp = new uchar[size];
memcpy(temp, cv_img.data, size);
HalconCpp::GenImage1(&H_img, "byte", width, height, (Hlong)(temp));
delete[] temp;
}
else if (cv_img.channels() == 3)
{
int height = cv_img.rows, width = cv_img.cols;
int size = height * width;
uchar* B = new uchar[size];
uchar* G = new uchar[size];
uchar* R = new uchar[size];
for (int i = 0; i < height; i++)
{
uchar* p = cv_img.ptr<uchar>(i);
for (int j = 0; j < width; j++)
{
B[i * width + j] = p[3 * j];
G[i * width + j] = p[3 * j + 1];
R[i * width + j] = p[3 * j + 2];
}
}
HalconCpp::GenImage3(&H_img, "byte", width, height, (Hlong)(R), (Hlong)(G), (Hlong)(B));
delete[] R;
delete[] G;
delete[] B;
}
return H_img;
}
halcon转opencv
cv::Mat HImageToMat(HalconCpp::HObject& H_img)
{
cv::Mat cv_img;
HalconCpp::HTuple channels, w, h;
HalconCpp::ConvertImageType(H_img, &H_img, "byte");
HalconCpp::CountChannels(H_img, &channels);
if (channels.I() == 1)
{
HalconCpp::HTuple pointer;
GetImagePointer1(H_img, &pointer, nullptr, &w, &h);
int width = w.I(), height = h.I();
int size = width * height;
cv_img = cv::Mat::zeros(height, width, CV_8UC1);
memcpy(cv_img.data, (void*)(pointer.L()), size);
}
else if (channels.I() == 3)
{
HalconCpp::HTuple pointerR, pointerG, pointerB;
HalconCpp::GetImagePointer3(H_img, &pointerR, &pointerG, &pointerB, nullptr, &w, &h);
int width = w.I(), height = h.I();
int size = width * height;
cv_img = cv::Mat::zeros(height, width, CV_8UC3);
uchar* R = (uchar*)(pointerR.L());
uchar* G = (uchar*)(pointerG.L());
uchar* B = (uchar*)(pointerB.L());
for (int i = 0; i < height; ++i)
{
uchar* p = cv_img.ptr<uchar>(i);
for (int j = 0; j < width; ++j)
{
p[3 * j] = B[i * width + j];
p[3 * j + 1] = G[i * width + j];
p[3 * j + 2] = R[i * width + j];
}
}
}
return cv_img;
}