C++ OpenCV【解决putText不能显示中文】

本文提供了一种在OpenCV中显示中文的方法,通过Windows GDI显示系统和TrueType字体,实现了中文字符的有效显示。此方法适用于C++环境,并提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        使用cv::putText写中文字符时输出结果为"??????"。。。。。。这怎么能忍?

        python方法中可以将opencv图片转化为PIL,写中文之后再转回opencv格式。

        C++方法中通常利用freetype库来实现,freetype打包的win32静态库可以在C#通过dll引用进行调用,这需要其版本跟CvxText对应,否则会出现错误,其在x64平台也一样。

        本文采用windows的GDI显示系统的TrueType字体,没有封装,就两个函数,分成h和cpp文件,可以自己编辑文件名和函数名,也可以直接将cpp的代码复制到你需要的程序中。


 【putText.h】

#ifndef PUTTEXT_H_
#define PUTTEXT_H_

#include <windows.h>
#include <string>
#include <opencv2/opencv.hpp>

using namespace cv;

void GetStringSize(HDC hDC, const char* str, int* w, int* h);
void putTextHusky(Mat &dst, const char* str, Point org, Scalar color, int fontSize,
	const char *fn = "Arial", bool italic = false, bool underline = false);

#endif // PUTTEXT_H_

  【putText.cpp】

#include "putText.h"

void GetStringSize(HDC hDC, const char* str, int* w, int* h)
{
	SIZE size;
	GetTextExtentPoint32A(hDC, str, strlen(str), &size);
	if (w != 0) *w = size.cx;
	if (h != 0) *h = size.cy;
}

void putTextHusky(Mat &dst, const char* str, Point org, Scalar color, int fontSize, const char* fn, bool italic, bool underline)//后俩参数:斜体,下划线
{
	CV_Assert(dst.data != 0 && (dst.channels() == 1 || dst.channels() == 3));

	int x, y, r, b;
	if (org.x > dst.cols || org.y > dst.rows) return;
	x = org.x < 0 ? -org.x : 0;
	y = org.y < 0 ? -org.y : 0;

	LOGFONTA lf;
	lf.lfHeight = -fontSize;
	lf.lfWidth = 0;
	lf.lfEscapement = 0;
	lf.lfOrientation = 0;
	lf.lfWeight = 5;
	lf.lfItalic = italic;   //斜体
	lf.lfUnderline = underline; //下划线
	lf.lfStrikeOut = 0;
	lf.lfCharSet = DEFAULT_CHARSET;
	lf.lfOutPrecision = 0;
	lf.lfClipPrecision = 0;
	lf.lfQuality = PROOF_QUALITY;
	lf.lfPitchAndFamily = 0;
	strcpy_s(lf.lfFaceName, fn);

	HFONT hf = CreateFontIndirectA(&lf);
	HDC hDC = CreateCompatibleDC(0);
	HFONT hOldFont = (HFONT)SelectObject(hDC, hf);

	int strBaseW = 0, strBaseH = 0;
	int singleRow = 0;
	char buf[1 << 12];
	strcpy_s(buf, str);
	char *bufT[1 << 12];  // 这个用于分隔字符串后剩余的字符,可能会超出。
	//处理多行
	{
		int nnh = 0;
		int cw, ch;

		const char* ln = strtok_s(buf, "\n", bufT);
		while (ln != 0)
		{
			GetStringSize(hDC, ln, &cw, &ch);
			strBaseW = max(strBaseW, cw);
			strBaseH = max(strBaseH, ch);

			ln = strtok_s(0, "\n", bufT);
			nnh++;
		}
		singleRow = strBaseH;
		strBaseH *= nnh;
	}

	if (org.x + strBaseW < 0 || org.y + strBaseH < 0)
	{
		SelectObject(hDC, hOldFont);
		DeleteObject(hf);
		DeleteObject(hDC);
		return;
	}

	r = org.x + strBaseW > dst.cols ? dst.cols - org.x - 1 : strBaseW - 1;
	b = org.y + strBaseH > dst.rows ? dst.rows - org.y - 1 : strBaseH - 1;
	org.x = org.x < 0 ? 0 : org.x;
	org.y = org.y < 0 ? 0 : org.y;

	BITMAPINFO bmp = { 0 };
	BITMAPINFOHEADER& bih = bmp.bmiHeader;
	int strDrawLineStep = strBaseW * 3 % 4 == 0 ? strBaseW * 3 : (strBaseW * 3 + 4 - ((strBaseW * 3) % 4));

	bih.biSize = sizeof(BITMAPINFOHEADER);
	bih.biWidth = strBaseW;
	bih.biHeight = strBaseH;
	bih.biPlanes = 1;
	bih.biBitCount = 24;
	bih.biCompression = BI_RGB;
	bih.biSizeImage = strBaseH * strDrawLineStep;
	bih.biClrUsed = 0;
	bih.biClrImportant = 0;

	void* pDibData = 0;
	HBITMAP hBmp = CreateDIBSection(hDC, &bmp, DIB_RGB_COLORS, &pDibData, 0, 0);

	CV_Assert(pDibData != 0);
	HBITMAP hOldBmp = (HBITMAP)SelectObject(hDC, hBmp);

	//color.val[2], color.val[1], color.val[0]
	SetTextColor(hDC, RGB(255, 255, 255));
	SetBkColor(hDC, 0);
	//SetStretchBltMode(hDC, COLORONCOLOR);

	strcpy_s(buf, str);
	const char* ln = strtok_s(buf, "\n", bufT);
	int outTextY = 0;
	while (ln != 0)
	{
		TextOutA(hDC, 0, outTextY, ln, strlen(ln));
		outTextY += singleRow;
		ln = strtok_s(0, "\n", bufT);
	}
	uchar* dstData = (uchar*)dst.data;
	int dstStep = dst.step / sizeof(dstData[0]);
	unsigned char* pImg = (unsigned char*)dst.data + org.x * dst.channels() + org.y * dstStep;
	unsigned char* pStr = (unsigned char*)pDibData + x * 3;
	for (int tty = y; tty <= b; ++tty)
	{
		unsigned char* subImg = pImg + (tty - y) * dstStep;
		unsigned char* subStr = pStr + (strBaseH - tty - 1) * strDrawLineStep;
		for (int ttx = x; ttx <= r; ++ttx)
		{
			for (int n = 0; n < dst.channels(); ++n) {
				double vtxt = subStr[n] / 255.0;
				int cvv = vtxt * color.val[n] + (1 - vtxt) * subImg[n];
				subImg[n] = cvv > 255 ? 255 : (cvv < 0 ? 0 : cvv);
			}

			subStr += 3;
			subImg += dst.channels();
		}
	}

	SelectObject(hDC, hOldBmp);
	SelectObject(hDC, hOldFont);
	DeleteObject(hf);
	DeleteObject(hBmp);
	DeleteDC(hDC);
}

        第二个函数putTextHusky(),默认使用Arial字体,也可以设置成操作系统中已经安装的字体,如“宋体”、“微软雅黑”、“Times New Roman”等;默认显示非斜体、非下划线。

【示例】

#include <opencv2/opencv.hpp>
#include "putText.h"

using namespace std;
using namespace cv;

int main()//自己写库解决putText无法显示中文字符问题
{
	Mat img = imread("lyf.png");

	putText(img, "中文无法显示...", Point(50, 50), 2, 1, Scalar(0, 0, 255), 1, 8, false);
	putTextHusky(img, "Arial字体...", Point(50, 100), Scalar(0, 0, 255), 30, "Arial");
	putTextHusky(img, "微软雅黑字体...", Point(50, 150), Scalar(0, 255, 0), 30, "微软雅黑", true, true);
	putTextHusky(img, "楷体字体...\n", Point(50, 200), Scalar(128, 255, 0), 30, "楷体", true, true);
	//imwrite("lyfWrite.png", img);
	imshow("test", img);
	waitKey(0);
	
	system("pause");
	return 0;
}

### C++ OpenCV `putText` 函数显示中文时出现乱码的解决方案 当使用OpenCV中的`putText`函数尝试绘制中文字符到图像上时,可能会遇到乱码问题。这是因为默认情况下,`putText`并不支持多字节编码的文字,比如汉字。 为了处理这个问题,可以采用自定义的方式加载字体并渲染文字。一种常见的做法是利用FreeType库来解析TTF(TrueType Font)文件,并将其应用到图片上的指定位置[^1]。 另一种更为简便的方法是在项目中引入专门针对此情况设计的支持中文显示的功能模块——例如,在给定的信息里提到过可以通过包含特定头文件`putTextCN.h`以及调用其中封装好的接口`putTextZH()`来进行操作[^2]: ```cpp #include "opencv2/opencv.hpp" #include "putTextCN.h" using namespace cv; int main() { // 加载测试图像 Mat img = imread("test.jpg"); // 定义要写入的内容(宽字符字符串) wchar_t* msg = L"我是一个粉刷匠,\n粉刷本领强."; // 调用putTextZH函数向图像添加中文文本 putTextZH(img, msg, Point(50, 50), Scalar(255, 0, 0), 10, "微软雅黑", false, false); imshow("Image with Chinese Text", img); waitKey(0); return 0; } ``` 上述代码片段展示了如何通过调用`putTextZH`函数实现将带有换行符的中文诗句正确地呈现在读取的一张名为“test.jpg”的照片之上;同时指定了文字的颜色为蓝色、字号大小为10px,并选择了系统中存在的“微软雅黑”作为目标字体样式。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值