实现 cv::Mat 转 QImage
| 552 | |
| 553 | // 实现 cv::Mat 转 QImage |
| 554 | QImage Utils::cvMat2QImage(const cv::Mat& mat) { |
| 555 | if (mat.empty()) { |
| 556 | return QImage(); |
| 557 | } |
| 558 | |
| 559 | switch (mat.type()) { |
| 560 | case CV_8UC1: { |
| 561 | // 单通道灰度图 |
| 562 | QImage image(mat.cols, mat.rows, QImage::Format_Grayscale8); |
| 563 | memcpy(image.bits(), mat.data, static_cast<size_t>(mat.cols * mat.rows)); |
| 564 | return image; |
| 565 | } |
| 566 | case CV_8UC3: { |
| 567 | // 三通道彩色图 (BGR to RGB) |
| 568 | QImage image(mat.cols, mat.rows, QImage::Format_RGB888); |
| 569 | for (int row = 0; row < mat.rows; ++row) { |
| 570 | memcpy(image.scanLine(row), mat.ptr(row), static_cast<size_t>(mat.cols * 3)); |
| 571 | } |
| 572 | return image.rgbSwapped(); // BGR -> RGB |
| 573 | } |
| 574 | case CV_8UC4: { |
| 575 | // 四通道带透明度图 (BGRA to RGBA) |
| 576 | QImage image(mat.cols, mat.rows, QImage::Format_ARGB32); |
| 577 | for (int row = 0; row < mat.rows; ++row) { |
| 578 | memcpy(image.scanLine(row), mat.ptr(row), static_cast<size_t>(mat.cols * 4)); |
| 579 | } |
| 580 | return image; |
| 581 | } |
| 582 | default: |
| 583 | return QImage(); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | // 实现 QImage 转 cv::Mat |
| 588 | cv::Mat Utils::qImage2CvMat(const QImage& image) { |