@TOC
问题描述
当需要将OCR结果添加到图片保存时总是报错误,错误类型为“UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xd6 in position 40: invalid continuation byte”
常见解决办法
原来: df.to_csv(outpath)
修改为: df.to_csv(outpath, encoding= u’utf-8’)
这样就可以按utf-8方式读取了。
我的解决办法
但是这种解决办法因人而异,我按网上的解决办法将字符处理编码方式变为utf8后发现还是报这个错误,因此可以断定出错方式不是utf8的问题,后来参考了其他解决办法后发现中文编码在Python中应该用‘gbk’。下文附改正后的代码。
代码
f=open('paul_train_log.txt','r')
c=f.readline()
while c != '':
img = cv2.imread('./chi.jpg')
if len(c.split('%')) == 2:
score = int(c.split('%')[0].split(':')[1].strip())
if score > 0:
classes = int(c.split('%')[0].split(':')[0].strip())
if len(c.split('box')) == 2:
box = c.split(' ')
x = int(box[1])
w = int(box[2])
y = int(box[3])
h = int(box[4])
cv2.rectangle(img, (x, y), (w, h), (0, 255, 0), 2)
# print(classes)
cv2.imwrite('chi.jpg', img)
print(chi[classes])
# cv2.putText(img, chi[classes], (x-1, y-10), cv2.FONT_HERSHEY_PLAIN, 2.0, (255, 255, 255), 2, 1)
img_OpenCV = cv2.imread('chi.jpg')
img_PIL = Image.fromarray(cv2.cvtColor(img_OpenCV, cv2.COLOR_BGR2RGB))
font = ImageFont.truetype('font/AdobeFangsongStd-Regular.otf', 30)
fillColor = (25, 10, 0)
position = (x - 1, y - 10)
'''if isinstance(chi[classes], unicode)==True:
print('888888888888888888888')'''
s='jinri'
draw = ImageDraw.Draw(img_PIL)
print(chi[classes])
draw.text(position, chi[classes],font=font, fill=fillColor)
img_OpenCV = cv2.cvtColor(numpy.asarray(img_PIL), cv2.COLOR_RGB2BGR)
cv2.imshow("print chinese to image", img_OpenCV)
cv2.waitKey()
cv2.imwrite('chi.jpg', img_OpenCV)
c = f.readline()
后记
实现效果:
draw.text(position, chi[classes],font=font, fill=fillColor)
font类型根据自己需要设定,可以使用默认font,即可以不写这个参数。
有效请点赞,谢谢!
版权声明:本文为weixin_42343812原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。