OpenCV实现图像上添加汉字

  OpenCV已经更新至3.0了,但自带函数putText依然不支持图像上添加汉字,所以下面实现了图像中添加汉字功能,话不多说,代码奉上。

<span style="font-size:18px;">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 paDrawString(Mat& dst, const char* str, Point org, Scalar color, int fontSize, 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 (lf.lfFaceName, "华文行楷" );

	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(buf, str);

	//处理多行
	{
		int nnh = 0;
		int cw, ch;
		const char* ln = strtok(buf, "\n");
		while(ln != 0)
		{
			GetStringSize(hDC, ln, &cw, &ch);
			strBaseW = max(strBaseW, cw);
			strBaseH = max(strBaseH, ch);

			ln = strtok(0, "\n");
			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(buf, str);
	const char* ln = strtok(buf, "\n");
	int outTextY = 0;
	while(ln != 0)
	{
		TextOutA(hDC, 0, outTextY, ln, strlen(ln));
		outTextY += singleRow;
		ln = strtok(0, "\n");
	}
	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);
}


调用demo如下:

void main()
{
	Mat img = imread("cat.jpg");
	if(!img.data)
	{
		cout<<"load image error"<<endl;
		return;
	}
	paDrawString(img, "测试汉字哈...\n换行了哟\n真的可以啊!!!~",Point(10, 10), Scalar(255,0,0), 50, true, true);
	imshow("img", img);
	waitKey();
}


实现的效果如图所示:

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
要在图像添加中文文字,你可以使用OpenCV和Python中的中文字体文件。下面是一个示例代码,演示了如何在图像添加中文文字: ```python import cv2 import numpy as np from PIL import ImageFont, ImageDraw, Image # 读取图像 image = cv2.imread("image.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_pil = Image.fromarray(image) # 转换为PIL的ImageDraw对象 draw = ImageDraw.Draw(image_pil) # 字体文件路径 font_path = "font.ttf" # 字体大小 font_size = 30 # 中文文字内容 text = "中文文字" # 加载中文字体文件 font = ImageFont.truetype(font_path, font_size) # 文字颜色 text_color = (255, 0, 0) # 获取文字尺寸 text_width, text_height = draw.textsize(text, font=font) # 文字位置 x = (image.shape[1] - text_width) // 2 y = (image.shape[0] - text_height) // 2 # 在图像上绘制中文文字 draw.text((x, y), text, font=font, fill=text_color) # 转换回OpenCV格式的图像 image_with_text = np.array(image_pil) image_with_text = cv2.cvtColor(image_with_text, cv2.COLOR_RGB2BGR) # 显示图像 cv2.imshow("Image with Text", image_with_text) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在这个示例中,我们首先使用OpenCV读取了图像(假设为"image.jpg"),然后将图像转换为PIL的Image格式,这样就可以使用PIL库中的ImageDraw对象进行绘制。接下来,我们定义了要添加的中文文字内容、字体文件路径和字体大小。然后,我们使用ImageFont.truetype函数加载中文字体文件,并使用draw.textsize函数获取文字的尺寸。接着,我们计算了文字的位置,并使用draw.text函数将中文文字绘制在图像上。最后,我们将绘制完成的图像转换回OpenCV格式,并显示出来。 请确保你已经安装了Pillow库(pip install Pillow)并准备了一张图像和一个中文字体文件。根据需要,你可以调整文字的内容、字体、大小和颜色以实现更多样化的效果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值