关于OpenCV无法putText汉字的坑

关于OpenCV无法在图片中写入汉字,网上很多文章,大多数是教你如何利用freetype2这个库写入汉字,本人试了一下,在ubuntu上效果不好,写入汉字时空格成了方格,而且汉字之间必须要隔个空格才能完整显示出来,否则总会漏字。如下图

我看了源码,是将字符串转换成unicode的编码,再通过freetype2中的FT_Get_Char_Index函数获取字符的索引。但是Linux下使用的是utf-8编码,问题应该就出在这里。

        其实在OpenCV 3.2以后,已经集成了freetype库,写入中文其实有更简单的方法,直接调用OpenCV中的freetype就可以了,使用非常简单,代码如下:

 

#include <opencv2/core/core.hpp>
#include<opencv2/freetype.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include<iostream>
#include <string>
using namespace std;

int main()
{
	cv::Mat img=cv::imread("/home/图片/Plates/abc.jpg");
	
	string text="这次肯定能Put上中文!";
	
	int fontHeight=60;
	int thickness=-1;
	int linestyle=8;
	int baseline=0;

	cv::Ptr<cv::freetype::FreeType2> ft2;
	ft2=cv::freetype::createFreeType2();
	ft2->loadFontData("/usr/share/fonts/winFonts/simkai.ttf",0);
	
	cv::Size textSize=ft2->getTextSize(text,fontHeight,thickness,&baseline);

	if (thickness>0) baseline+=thickness;

	// center the text
	cv::Point textOrg((img.cols - textSize.width) / 2,
              (img.rows + textSize.height) / 2);
	// draw the box
	cv::rectangle(img, textOrg + cv::Point(0, baseline),
          textOrg + cv::Point(textSize.width, -textSize.height),
          cv::Scalar(0,255,0),1,8);
	// ... and the baseline first
	cv::line(img, textOrg + cv::Point(0, thickness),
     textOrg + cv::Point(textSize.width, thickness),
     cv::Scalar(0, 0, 255),1,8);
	// then put the text itself
	ft2->putText(img, text, textOrg, fontHeight,
             cv::Scalar(255,0,0), thickness, linestyle, true );

	cv::imshow("效果",img);
	if (cv::waitKey(0)==27) return 0;
}

效果图:

  • 12
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值