说明:通过qt5的摄像头得到QImage图像
h文件
#ifndef WIN_H #define WIN_H #include <QWidget> #include <QDebug> #include "Halcon.h" #include "HalconCpp.h" #include "HDevThread.h" #include <string> #include<opencv2/opencv.hpp> #include <QLabel> #include <QImage> #include <QThread> #include <thread> //C++多线程头文件 #include <QCamera> //导入摄像头类 #include <QCameraInfo> //摄像头信息类 #include <QCameraViewfinder> //取景器类 #include <QCameraImageCapture> //捕获类 #include <QCameraViewfinderSettings> //摄像头设置类 #include <QPushButton> using namespace HalconCpp; class Win : public QWidget { Q_OBJECT public: Win(QWidget *parent = nullptr); ~Win(); QCamera *camera; //摄像头对象 QCameraImageCapture *imageCapture;//捕获对象 QPushButton* buttonCapture; HObject hObject; HTuple hv_WindowHandle,hv_Width, hv_Height; HObject QImageToHObject(QImage image);//Qt彩色转Halcon彩色 private slots: void displayImage(int,QImage); void captureImage(); }; #endif // WIN_H
cpp文件
#include "win.h" Win::Win(QWidget *parent) : QWidget(parent) { this->resize(800,500); buttonCapture=new QPushButton("捕获",this); buttonCapture->move(700,400); camera=new QCamera(this); imageCapture=new QCameraImageCapture(camera);//捕获对象 connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(displayImage(int,QImage))); connect(buttonCapture, SIGNAL(clicked()), this, SLOT(captureImage())); camera->start(); } Win::~Win() { } void Win::displayImage(int id, QImage image) { qDebug()<<"id="<<id; hObject=QImageToHObject(image); GetImageSize(hObject, &hv_Width, &hv_Height); SetWindowAttr("background_color","black"); OpenWindow(0,0,hv_Width, hv_Height,0,"visible","",&hv_WindowHandle); DispObj(hObject, hv_WindowHandle); } void Win::captureImage() //按钮槽函数 { imageCapture->capture();//捕获图片 } HObject Win::QImageToHObject(QImage image) //QImage彩色转Halcon彩色 { //注意:在使用这个函数之前,最好先判断图像是否三通道 unsigned char *data=image.bits();//获取图像像素字节数据的首地址 int width=image.width();//图像宽 int height=image.height();//图像高 unsigned char* dataRed=(unsigned char*)malloc(width*height);//存储处理后的数据 unsigned char* dataGreen=(unsigned char*)malloc(width*height);//存储处理后的数据 unsigned char* dataBlue=(unsigned char*)malloc(width*height);//存储处理后的数据 for (int i=0;i<height;i++){ for (int j=0;j<width;j++){ dataRed[i*width+j] =*(data+2); dataGreen[i*width+j]=*(data+1); dataBlue[i*width+j]=*data; data+=4; } } HObject Image; GenImage3(&Image, "byte", width, height, (Hlong)(dataRed), (Hlong)(dataGreen), (Hlong)(dataBlue)); return Image; }