![d6c75463d8829f1b984a9b50b13f60a8.png](https://img-blog.csdnimg.cn/img_convert/d6c75463d8829f1b984a9b50b13f60a8.png)
前言
把中文字符输出到Mat图片上,英文字符没什么问题,但是OpenCV 的putText函数不能输出中文,会出现乱码。网上普遍的解决方案是使用freetype库来输出中文,结果还是乱码。因此介绍一种方式解决该问题。
一、加载头文件
#include "stdafx.h"
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <locale.h>
#include <wchar.h>
#include <windows.h>
using namespace std;
using namespace cv;
二、重新putText函数,这边修改为putTextZH
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 putTextZH(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);
}
三、中文计数问题
如果使用char * str = "ABCDE你好啊",用strlen(str)得到的结果不是8,而是11,因为英文占一个字节,中文占两个字节。所以可以使用wchar_t* str = "ABCDE你好啊",用wcslen(str),此时得到的是8。
四、wchar_t* 转为char *类型,因为putTextZH用的是char *类型。
//将宽字节wchar_t*转化为单字节char*
char* UnicodeToAnsi(wchar_t* szStr)
{
int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, 1, NULL, 0, NULL, NULL);
if (nLen == 0)
{
return NULL;
}
char* pResult = new char[nLen+1];
WideCharToMultiByte(CP_ACP, 0, szStr, nLen, pResult, nLen, NULL, NULL);
pResult[nLen] = '0';
return pResult;
}
五、测试putTextZH输出中文到Mat的代码,这边测试一个简单实例,自定义一个大小的图片,在图片内自动适应文字的大小,把文字输出到图片上。
//字符自动换行算法,支持中文,自动适应字符大小
Mat wordNewLine(int input_width, int input_height, wchar_t* input_string)
{
setlocale(LC_CTYPE, "chs");
Mat dst(cv::Size(input_width, input_height), CV_8UC1, Scalar(255));
int strlength = wcslen(input_string);
int lineWidth = sqrt(strlength) + 1;
int split_cols, split_rows;
if (input_width >= input_height)
{
split_cols = lineWidth;
split_rows = ceil(strlength * 1.0 / split_cols);
}
else
{
split_rows = lineWidth;
split_cols = ceil(strlength * 1.0 / split_rows);
}
int character_w = input_width / split_cols;
int character_h = input_height / split_rows;
vector<int> center_x, center_y;
for (int i = 1; i <= split_rows*split_cols; i++)
{
int x_i = i%split_cols;
int x_j = i%split_rows;
if (x_i == 0)
x_i = split_cols;
if (x_j == 0)
x_j = split_rows;
center_x.push_back((character_w * x_i) - character_w / 2);
center_y.push_back((character_h * x_j) - character_h / 2);
}
sort(center_y.begin(), center_y.end());
for (int i = 0; i < strlength; i++)
{
wchar_t str_single = input_string[i];
char * single_char = UnicodeToAnsi(&str_single);
int fontSize = character_w < character_h ? character_w : character_h;
putTextZH(dst, single_char, cv::Point(center_x.at(i) - (fontSize * 72 / 96) / 2, center_y.at(i) - (fontSize * 72 / 96) / 2), Scalar(0), fontSize * 72 / 96, "宋体", false, false);
}
return dst;
}
int _tmain(int argc, _TCHAR* argv[])
{
int input_width = 1000;
int input_height = 1000;
wchar_t* input_string = L"字符自动换行算法测试结果ABCDEFG123456";
Mat dst = wordNewLine(input_width, input_height, input_string);
imwrite("./result.bmp", dst);
imshow("result", dst);
cvWaitKey(0);
return 0;
}
最后
如果觉得文章对您有帮助的话,别忘了给我个赞,谢谢!