文章目录
1、opencv读取中文路径图片2、opencv保存中文路径图片3、图片转base644、base64转图片有几点要注意
cv2.imread(filename,flags)cv2.imwrite(filename,img)cv2.imdecode(data,flags)cv2.imencode(ext,img)
flags有几点(这里只列3点):
1、opencv读取中文路径图片
import cv2import numpy as npimg_data = np.fromfile(图片.jpg, np.uint8)img = cv2.imdecode(img_data, -1)# 此法可读取中文路径图片,读取后为BRG模式img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
2、opencv保存中文路径图片
当然保存英文路径图片也是没有问题的
#此时的img需要是BGR格式cv2.imencode('.jpg', img)[1].tofile(picPath+"test.jpg")
3、图片转base64
import base64data1 = base64.b64encode(open('dog.jpg','rb').read())#以下两种方法都行#data2 = str(data1, encoding='utf-8')data2 = data1.decode('utf-8')
data1是字节,data2是字符串,如果需要保存可以看以下保存和读取代码:
with open('test1.txt','wb') as f:f.write(data1)with open('test2.txt','w') as f:f.write(data2)with open('test1.txt','rb') as f:data11 = f.read()with open('test2.txt','r') as f:data22=f.read()
以上data1和data2都是正确的,但在前后端交互时,前端传来的数据是data2这种格式。
4、base64转图片
上文中data1和data2解码后结果相同
import base64im1 = base64.b64decode(data1)im2 = base64.b64decode(data2)#im1==im2img11 = cv2.imdecode(np.asarray(bytearray(im1),dtype=np.uint8),-1)img12 = cv2.imdecode(np.frombuffer(im1,dtype=np.uint8),-1)np.testing.assert_almost_equal(img11,img12)img21 = cv2.imdecode(np.asarray(bytearray(im2),dtype=np.uint8),-1)img22 = cv2.imdecode(np.frombuffer(im2,dtype=np.uint8),-1)np.testing.assert_almost_equal(img21,img22)np.testing.assert_almost_equal(img11,img21)#以上四行说明全部相同img4=cv2.imread('dog.jpg',-1)#读取原图方法1np.testing.assert_almost_equal(img4,img11)img5=cv2.imdecode(np.fromfile('dog.jpg',np.uint8),1)#读取原图方法2np.testing.assert_almost_equal(img4,img5)
以上用不同的方式来读取图像,所得结果全部一样,得到图片,可以进行保存,有两种保存方式:
#第一种cv2.imwrite('dog1.jpg',img11)#第二种with open('dog2.jpg','wb') as f:f.write(im2) #im1==im2的