分享

成功解决cv2.imwrite(filename, img)代码输出中文文件乱码的问题(cv2.imencode方法解决)

 处女座的程序猿 2021-09-28

成功解决cv2.imwrite(filename, img)代码输出中文文件乱码的问题(cv2.imencode方法解决)


解决问题

cv2.imwrite(filename, img)代码,输出中文文件乱码的问题

解决思路

中文乱码,利用imencode方法,cv2.imencode('.jpg', img)[1].tofile(filename) 

cv2.imdecode()函数:从指定的内存缓存中读取数据,并把数据转换(解码)成图像格式;主要用于从网络传输数据中恢复出图像。
cv2.imencode()函数:是将图片格式转换(编码)成流数据,赋值到内存缓存中;主要用于图像数据格式的压缩,方便网络传输。

1、从网络读取图像数据并转换成图片格式

# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
 
url = 'http://www./wp-content/uploads/2015/01/google_logo.png'
resp = urllib.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('URL2Image',image)
cv2.waitKey()


2、将图片编码到缓存,并保存到本地

# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
 
img = cv2.imread('0122.jpg')
# '.jpg'表示把当前图片img按照jpg格式编码,按照不同格式编码的结果不一样
img_encode = cv2.imencode('.jpg', img)[1]
# imgg = cv2.imencode('.png', img)
 
data_encode = np.array(img_encode)
str_encode = data_encode.tostring()
 
# 缓存数据保存到本地
with open('img_encode.txt', 'w') as f:
    f.write(str_encode)
    f.flush

参考文章
OpenCV-Python cv2.imdecode()和cv2.imencode() 图片解码和编码

解决方法


cv2.imwrite(filename, img)
改为
cv2.imencode('.jpg', img)[1].tofile(filename) 

哈哈,大功告成!

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约