python2和python3实现在图片上加汉字的方法


Posted in Python onAugust 22, 2019

python2和python3实现在图片上加汉字,最主要的区别还是内部编码方式不一样导致的,在代码上表现为些许的差别。理解了内部编码原理也就不会遇到这些问题了,以下代码是在WIN10系统上时测好用的。

Python2 在图片上加汉字代码实现

# -*- coding: cp936 -*-
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def ID_2_Word(txt):
 tmp_ID = txt.split(':')[0]
 value = txt.split(':')[-1]
 '''
 numbers = {
  'DS041' : "Coolant TEMP   ",
  'DS048' : "RPM     ",
  'DS049' : "Speed     ",
  'DS098' : "Oil level    ",
  'DS123' : "Control Module Voltage"
 }
 '''
 numbers = {
  'DS041' : "冷却液温度",
  'DS048' : "发动机转速",
  'DS049' : "车速 ",
  'DS098' : "燃油液位输入",
  'DS123' : "控制模块电压"
 }
 word = numbers.get(tmp_ID, None)
 result = str(word) + ':' + value
 #print(result)
 return result
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
 if (isinstance(img, np.ndarray)): #判断是否OpenCV图片类型
  img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
 draw = ImageDraw.Draw(img)
 #fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
 fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="gb2312") #cp936
 draw.text((left, top), text, textColor, font=fontText)
 return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
def layer1_show(img,data):
 frame = cv2.resize(img, (1280, 720), interpolation=cv2.INTER_CUBIC)
 font = ImageFont.truetype('font/simsun.ttc',24,encoding="utf-8")
 OBD_string = data
 y0, dy = 50, 25
 for i, txt in enumerate(OBD_string.split(';')):
   #word = txt
  word = ID_2_Word(txt) #将OBD信号的ID转换为中文
  word = unicode(word,'gbk')
   #print(i, txt.split(':')[0])
  y = y0+i*dy
  frame = cv2ImgAddText(frame, word, 100, y, (255, 0, 0), 20)
 cv2.imshow("layer_1", frame)
 cv2.waitKey(0)
if __name__ == '__main__':
 img = cv2.imread("map.png");
 data = "DS041: 88;DS048: 800;DS049: 64;DS098: 0.00;DS123: 0.00"
 layer1_show(img,data)

python2和python3实现在图片上加汉字的方法

Python3 在图片上加汉字代码实现

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def ID_2_Word(txt):
 tmp_ID = txt.split(':')[0]
 value = txt.split(':')[-1]
 '''
 numbers = {
  'DS041' : "Coolant TEMP   ",
  'DS048' : "RPM     ",
  'DS049' : "Speed     ",
  'DS098' : "Oil level    ",
  'DS123' : "Control Module Voltage"
 }
 '''
 numbers = {
  'DS041' : "冷却液温度",
  'DS048' : "发动机转速",
  'DS049' : "车速 ",
  'DS098' : "燃油液位输入",
  'DS123' : "控制模块电压"
 }
 word = numbers.get(tmp_ID, None)
 result = str(word) + ':' + value
 #print(result)
 return result
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
 if (isinstance(img, np.ndarray)): #判断是否OpenCV图片类型
  img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
 draw = ImageDraw.Draw(img)
 #fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
 fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="gb2312") #cp936
 draw.text((left, top), text, textColor, font=fontText)
 return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
def layer1_show(img,data):
 frame = cv2.resize(img, (1280, 720), interpolation=cv2.INTER_CUBIC)
 font = ImageFont.truetype('font/simsun.ttc',24,encoding="utf-8")
 OBD_string = data
 y0, dy = 50, 25
 for i, txt in enumerate(OBD_string.split(';')):
   #word = txt
  word = ID_2_Word(txt) #将OBD信号的ID转换为中文
  #word = unicode(word,'gbk')
  y = y0+i*dy
  frame = cv2ImgAddText(frame, word, 100, y, (255, 0, 0), 20)
 cv2.imshow("layer_1", frame)
 cv2.waitKey(0)
if __name__ == '__main__':
 img = cv2.imread("map.png");
 data = "DS041: 88;DS048: 800;DS049: 64;DS098: 0.00;DS123: 0.00"
 layer1_show(img,data)

python2和python3实现在图片上加汉字的方法

遇到的问题

python2中:UnicodeDecodeError: ‘ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128)

这是因为这是因为默认的是utf-8编码格式

中文字符的Unicode编码0x0800-0xFFFF之间,(utf-8包含了部分汉字)
当你试图将该“中文字符”转成U码的utf-8时超出了其范筹
而GBK 规范收录了 ISO 10646.1 中的全部 CJK 汉字和符号,并有所补充,
所以解决方法是将utf-8改为gbk

word = unicode(word,'utf-8') 改为 word = unicode(word,'gbk')

总结

以上所述是小编给大家介绍的python2和python3实现在图片上加汉字的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
Python 文件和输入输出小结
Oct 09 Python
详解python 发送邮件实例代码
Dec 22 Python
python中pandas.DataFrame对行与列求和及添加新行与列示例
Mar 12 Python
Python FTP两个文件夹间的同步实例代码
May 25 Python
python3实现爬取淘宝美食代码分享
Sep 23 Python
Django实现微信小程序的登录验证功能并维护登录态
Jul 04 Python
Django中的用户身份验证示例详解
Aug 07 Python
Python如何应用cx_Oracle获取oracle中的clob字段问题
Aug 27 Python
解析PyCharm Python运行权限问题
Jan 08 Python
Python-opencv 双线性插值实例
Jan 17 Python
pytorch torchvision.ImageFolder的用法介绍
Feb 20 Python
Python是什么 Python的用处
May 26 Python
Python使用微信itchat接口实现查看自己微信的信息功能详解
Aug 22 #Python
简单了解python 生成器 列表推导式 生成器表达式
Aug 22 #Python
Python实现的微信红包提醒功能示例
Aug 22 #Python
Python PIL图片添加字体的例子
Aug 22 #Python
在python image 中安装中文字体的实现方法
Aug 22 #Python
解决Python3用PIL的ImageFont输出中文乱码的问题
Aug 22 #Python
用Pelican搭建一个极简静态博客系统过程解析
Aug 22 #Python
You might like
初步介绍PHP扩展开发经验分享
2012/09/06 PHP
php读取csv文件后,uft8 bom导致在页面上显示出现问题的解决方法
2013/08/10 PHP
PHP的PSR规范中文版
2013/09/28 PHP
php遍历文件夹下的所有文件和子文件夹示例
2014/03/20 PHP
phplist及phpmailer(组合使用)通过gmail发送邮件的配置方法
2016/03/30 PHP
总结PHP中初始化空数组的最佳方法
2019/02/13 PHP
Gambit vs ForZe BO3 第二场 2.13
2021/03/10 DOTA
javascript vvorld 在线加密破解方法
2008/11/13 Javascript
javascript面向对象编程(一) 实例代码
2010/06/25 Javascript
js实现的倒计时按钮实例
2015/06/24 Javascript
JS获取下拉框显示值和判断单选按钮的方法
2015/07/09 Javascript
jQuery实现的placeholder效果完整实例
2016/08/02 Javascript
JS判断form内所有表单是否为空的简单实例
2016/09/09 Javascript
js仿小米官网图片轮播特效
2016/09/29 Javascript
vux uploader 图片上传组件的安装使用方法
2018/05/15 Javascript
深入理解react 组件类型及使用场景
2019/03/07 Javascript
Node爬取大批量文件的方法示例
2019/06/28 Javascript
Python交换变量
2008/09/06 Python
python私有属性和方法实例分析
2015/01/15 Python
速记Python布尔值
2017/11/09 Python
python集合能干吗
2020/07/19 Python
python用tkinter实现一个gui的翻译工具
2020/10/26 Python
python入门教程之基本算术运算符
2020/11/13 Python
介绍一下游标
2012/01/10 面试题
黄继光的英雄事迹材料
2014/02/13 职场文书
代办委托书怎样写
2014/04/08 职场文书
副科级后备干部考察材料
2014/05/15 职场文书
健康状况证明模板
2014/10/23 职场文书
2014年党支部工作总结
2014/11/13 职场文书
期末考试复习计划
2015/01/19 职场文书
订货会主持词
2015/07/01 职场文书
巾帼建功标兵先进事迹材料
2016/02/29 职场文书
浅谈css实现背景颜色半透明的两种方法
2021/12/06 HTML / CSS
详解nginx location指令
2022/01/18 Servers
详解Flutter和Dart取消Future的三种方法
2022/04/07 Java/Android
Java异常体系非正常停止和分类
2022/06/14 Java/Android