Qt与OpenCV编程:在QLabel加载的图像上画矩形并剪切
生活随笔
收集整理的這篇文章主要介紹了
Qt与OpenCV编程:在QLabel加载的图像上画矩形并剪切
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
1.使用Qt與OpenCV做開發時,時常會用到鼠標與圖像交互這塊,OpenCV有自己的鼠標事件,但要在Qt搭建的界面上是不能使用OpenCV封裝的鼠標事件,Qt有自己的鼠標事件。
2.Qt鼠標事件:
3.要在QLabel里的畫矩形并按所畫的矩形剪切圖像,要重寫鼠標事情,然后結合OpenCV的ROI把圖像剪切出來,運行效果如下:
代碼
#include "mousechoose.h"MouseChoose::MouseChoose(QWidget *parent) : QLabel(parent) {setMouseTracking(true);//圖像大小自動調整為Qlabel大小//setScaledContents(true);is_pressed = false; }MouseChoose::~MouseChoose() {}void MouseChoose::loadMat(cv::Mat &src) {qt_img = matToQImage(src);cv_src = src;qt_pixmap = QPixmap::fromImage(qt_img); }void MouseChoose::paintEvent(QPaintEvent *e) {QLabel::paintEvent(e);QPainter painter(this);//設置畫筆,顏色、寬度QPen pen;pen.setColor(Qt::red);pen.setWidth(2);painter.setPen(pen);//painter.drawPixmap(0, 0, this->width(), this->height(), qt_pixmap);//painter.setViewport(0, 0, this->width(), this->height());if (is_pressed){qt_rect = QRect(start_point, end_point);painter.drawRect(qt_rect);} }void MouseChoose::mousePressEvent(QMouseEvent *e) {if (e->buttons()&Qt::LeftButton){start_point = e->pos();end_point = e->pos();is_pressed = true;}update();QLabel::mousePressEvent(e); }void MouseChoose::mouseReleaseEvent(QMouseEvent *e) {is_pressed = false;if (e->button() == Qt::LeftButton){if (start_point.x() > end_point.x() && start_point.y() > end_point.y()){QPoint tmp = start_point;start_point = end_point;end_point = tmp;}getDistrict();} }void MouseChoose::mouseMoveEvent(QMouseEvent *e) {if (e->buttons()&Qt::LeftButton){if (is_pressed){end_point = e->pos();update();}} }void MouseChoose::getDistrict() {int width = abs(end_point.x() - start_point.x());int height = abs(end_point.y() - start_point.y());double w_scale_value = double(qt_pixmap.width()) / double(this->width());double h_scale_value = double(qt_pixmap.height()) / double(this->height());cv_rect.x = start_point.x()*w_scale_value;cv_rect.y = start_point.y()*h_scale_value;cv_rect.width = width*w_scale_value;cv_rect.height = height*h_scale_value;//顯示roi截圖cv_dst = cv_src(cv_rect).clone();cv::namedWindow("src", 0);cv::imshow("src", cv_dst); }void MouseChoose::mouseDoubleClickEvent(QMouseEvent *e) {if (e->buttons()&Qt::LeftButton){double_point = e->pos();double w_scale_value = double(qt_pixmap.width()) / double(this->width());double h_scale_value = double(qt_pixmap.height()) / double(this->height());cv_point.x = double_point.x()*w_scale_value;cv_point.y = double_point.y()*h_scale_value;} }總結
以上是生活随笔為你收集整理的Qt与OpenCV编程:在QLabel加载的图像上画矩形并剪切的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QT多界面之间数据传输
- 下一篇: Qt与OpenCV编程:在子线程打开摄像