OpenCV+Python+PIL在图片中显示中文汉字

1.环境:windows10、Python3.6、OpenCV3.x、PIL;IDE:pycharm5.0.3

2.读取图片:

read_image.py

from PIL import Image,ImageDraw,ImageFont
import  cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("viking.jpg")
pil_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
pilimg = Image.fromarray(pil_img)
cv2.imshow("origial",img)
cv2.imshow(pilimg)
cv2.waitKey()
cv2.destroyAllWindows()

本想试试用cv2.imshow()函数显示pilimg,但提示出错:

Traceback (most recent call last):
  File "G:/Python_work/test/测试图片显示中文.py", line 11, in 
    cv2.imshow("pilimg",pilimg)
TypeError: mat is not a numpy array, neither a scalar

证明经过Image.fromarray()函数转换后的图片已经不是数组格式,而cv2.imshow()函数是读取数组类型的图片的,想显示转换后的图片可用plt.imshow().关于Image.fromarray()函数可百度。

如下:

from PIL import Image,ImageDraw,ImageFont
import  cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("viking.jpg")
pil_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
pilimg = Image.fromarray(pil_img)
cv2.imshow("origil",img)
plt.imshow(pilimg)
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()

3.图片显示中文汉字的方法

from PIL import Image,ImageDraw,ImageFont
import  cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("viking.jpg")#如想读取中文名称的图片文件可用cv2.imdecode()
pil_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)#cv2和PIL中颜色的hex码的储存顺序不同,需转RGB模式
pilimg = Image.fromarray(pil_img)#Image.fromarray()将数组类型转成图片格式,与np.array()相反
draw = ImageDraw.Draw(pilimg)#PIL图片上打印汉字
font = ImageFont.truetype("simhei.ttf",50,encoding="utf-8")#参数1:字体文件路径,参数2:字体大小;Windows系统“simhei.ttf”默认存储在路径:C:\Windows\Fonts中
draw.text((0,0),"维京人",(255,0,0),font=font)
cv2img = cv2.cvtColor(np.array(pilimg),cv2.COLOR_RGB2BGR)#将图片转成cv2.imshow()可以显示的数组格式
cv2.imshow("hanzi",cv2img)
cv2.waitKey()
cv2.destroyAllWindows()

结果如下:

OpenCV+Python+PIL在图片中显示中文汉字_第1张图片

 

你可能感兴趣的:(OpenCV+Python+PIL在图片中显示中文汉字)