03-HighGUI图形用户界面初步
HighGUI
HighGUI为高层GUI图形用户界面模块,包含媒体输入输出,视频捕捉,图像和视频编码解码,图形交互界面的接口等内容。
1、图像输入,输出,保存;
2、滑动条(Trackbar)使用;
3、OpenCV中鼠标操作;
图像输入,输出,保存;
1、Mat类是用于保存图像以及其他矩阵数据的数据结构,默认尺寸为0;
2、imread()
:
2、imshow()
:
3、imwrite()
:
4、push_back():
demo:
#include<opencv2/opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
void createAlphaMat(Mat &mat)
{
for (int row = 0; row < mat.rows; row++)
{
for (int col = 0; col < mat.cols; col++)
{
Vec4b &rgba = mat.at<Vec4b>(row, col);
rgba[0] = UCHAR_MAX; //0xff;
rgba[1] = saturate_cast<uchar>((float(mat.cols - col)) / ((float)mat.cols) * UCHAR_MAX);
rgba[2] = saturate_cast<uchar>((float(mat.rows - row)) / ((float)mat.rows) * UCHAR_MAX);
rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));
}
}
}
int main()
{
Mat mat(480, 640, CV_8UC4); //创建带alpha通道的Mat;
createAlphaMat(mat); //像素值填充
vector<int> compression_params;
//compression_params.push_back(IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
try {
imwrite("透明alpha图.png", mat, compression_params);
imshow("PNG图", mat);
waitKey(0);
}
catch (runtime_error & ex)
{
fprintf(stderr, "图像转换成PNG格式发生错误: %s\n", ex.what());
return -1;
}
return 0;
}
Trackbar
1、Trackbar依附于窗口而存在,必须与回调函数搭配使用:回调函数类型必须为 void XXXX(int ,void*)
;
2、getTrackbarPos()
: 返回当前轨迹条位置;
鼠标操作
1、指定鼠标操作消息回调函数为 : SetMouseCallback()
;
鼠标操作 demo:
#include <opencv2/opencv.hpp>
using namespace cv;
#define WINDOW_NAME "程序窗口"
void onMouseHandle(int event, int x, int y, int flags, void* param);
void DrawRectangle(Mat & img, Rect box);
void ShowHelpText();
Rect g_rectangle;
bool g_bDrawingBox = false;
RNG rng(12345);
int main(int argc, char** argv)
{
g_rectangle = Rect(-1, -1, 0, 0);
Mat srcImage(600, 800, CV_8UC3), tempImage;
namedWindow(WINDOW_NAME);
setMouseCallback(WINDOW_NAME, onMouseHandle,(void *) &srcImage);
while (1)
{
srcImage.copyTo(tempImage);
if (g_bDrawingBox) DrawRectangle(tempImage, g_rectangle);
imshow(WINDOW_NAME, tempImage);
if (waitKey(10) == 27) //ESC退出
{
break;
}
}
return 0;
}
void onMouseHandle(int event, int x, int y, int flags, void* param)
{
Mat &image = *(cv::Mat *) param;
switch (event)
{
case EVENT_MOUSEMOVE:
{
if (g_bDrawingBox)
{
g_rectangle.width = x - g_rectangle.x;
g_rectangle.height = y - g_rectangle.y;
}
}
break;
case EVENT_LBUTTONDOWN:
{
g_bDrawingBox = true;
g_rectangle = Rect(x, y, 0, 0); //记录起始点
}
break;
case EVENT_LBUTTONUP:
{
g_bDrawingBox = false;
if (g_rectangle.width < 0)
{
g_rectangle.x += g_rectangle.width;
g_rectangle.width *= -1;
}
if (g_rectangle.height < 0)
{
g_rectangle.y += g_rectangle.y;
g_rectangle.height *= -1;
}
DrawRectangle(image, g_rectangle);
}
break;
default:
break;
}
}
void DrawRectangle(Mat & img, Rect box)
{
rectangle(img, box, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)));//随机颜色
}
void ShowHelpText()
{
}