在Qt中解决opencv的putText函数无法绘制中文的一种解决方法

文章目录

1.问题

在opencv中,假如直接使用putText绘制中文,会在图像上出现问号,如下图所示:

2.查阅资料

查了一些资料,说想要解决这个问题,需要用到freetype库或者用opencv5(详情请查看文末的参考资料)。但是我现在用的是opencv4,freetype库已经被移到opencv_contrib去了,用起来麻烦,而且用freetype的话,其实也是相当于用了第三方库来实现:

cpp 复制代码
...
	cv::Ptr<cv::freetype::FreeType2> ft2;
	ft2=cv::freetype::createFreeType2();
...
	// then put the text itself
	ft2->putText(img, text, textOrg, fontHeight,
             cv::Scalar(255,0,0), thickness, linestyle, true );

那我Qt也是第三方库啊,还倒不如直接用Qt实现呢。

3.解决办法

于是,我实现了一个myPutText函数

cpp 复制代码
int myPutText(cv::Mat &img, QString text, QPoint org, QFont font, QPen pen)
{
    QImage::Format imgFormat;

    switch (img.channels()) {
    case 1:
        imgFormat = QImage::Format_Grayscale8;
        break;
    case 3:
        imgFormat = QImage::Format_RGB888; // 没有BGR格式,因此要注意一下pen的color
        break;
    default:
        return -1;
        break;
    }

		// 直接共享了Mat的内存,不存在内存复制。所以应该不怎么耗时
    QImage tmpImg(img.data, img.cols, img.rows, img.step, imgFormat);

    QPainter painter(&tmpImg);
    painter.setPen(pen);
    painter.setFont(font);
    painter.drawText(org, text);

    return 0;
}

用法如下:

cpp 复制代码
    cv::Mat img = cv::imread("4.bmp", cv::IMREAD_COLOR);
    cv::resize(img, img, cv::Size(640, 480));

    QString tempText = "中文";

    QPen pen;
    pen.setColor(QColor(0, 255, 0));

    QFont font;
    font.setPixelSize(32);

    myPutText(img, tempText, QPoint(100, 100), font, pen);

//    cv::putText(img, tempText.toStdString(), cv::Point(100, 100), cv::FONT_HERSHEY_TRIPLEX, 1.0, cv::Scalar(255, 255, 0));
    cv::imshow("img", img);

效果如下:


参考资料
【关于OpenCV无法putText汉字的坑】
【听说putText()支持中文了?!】

相关推荐
QX_hao2 小时前
【Go】--反射(reflect)的使用
开发语言·后端·golang
inferno2 小时前
Maven基础(二)
java·开发语言·maven
我是李武涯2 小时前
从`std::mutex`到`std::lock_guard`与`std::unique_lock`的演进之路
开发语言·c++
史不了3 小时前
静态交叉编译rust程序
开发语言·后端·rust
读研的武3 小时前
DashGo零基础入门 纯Python的管理系统搭建
开发语言·python
Andy4 小时前
Python基础语法4
开发语言·python
但要及时清醒4 小时前
ArrayList和LinkedList
java·开发语言
孚亭4 小时前
Swift添加字体到项目中
开发语言·ios·swift
hweiyu004 小时前
Go、DevOps运维开发实战(视频教程)
开发语言·golang·运维开发