python打开|显示|保存图片

1. 图片的打开与显示

PIL: jpg->RGB, png->RGBA; CV2: BGR;
Note that PIL and CV2 may have minor value differences

from PIL import Image
from matplotlib import pyplot as plt
import os

dir = 'C:/Users/user/Desktop/data/img.jpg'
img = Image.open(dir)	# image type: <class 'PIL.JpegImagePlugin.JpegImageFile'>
img.show()		  		# 调用windows照片查看器

plt.imshow(img)   		# 嵌入到开发环境比如jupyter中显示图片
plt.show()

img1 = Image.open(dir)							# img1: rgb
img1 = img1.resize((128, 128))					# (width, height)
img1 = Image.fromarray(np.array(img1))			

img2 = cv2.imread(path)      			        # image type: <class 'numpy.ndarray'>
img2 = img2[:, :, ::-1].copy()                  # bgr to rgb, way-1
# img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)  # bgr to rgb, way-2

img3 = mx.img.imread(path, to_rgb=False)	    # image type: mxnet NDArray
img3 = mx.img.resize_short(img3, 128)
img3,_ = mx.img.random_crop(img3,(112,112))		# img3: bgr
2. 图片的保存
cv2.imwrite('img3.jpg', img3.asnumpy())			# img3: mx_img_bgr

dir_ = 'C:/Users/user/Desktop/data/new_img.jpg'
img.save(dir_)
# img.save(dir_,format='jpg')

上面是静态指定了图片存储时用的新名,想要实现动态命名新名字的功能,先按如下尝试:

for i in range(10): 
    save_dir = os.path.join(dir_,str(i))
    img.save(save_dir,'jpg')

报错,KeyError,和其它一些信息,未解决。改为如下实现:

for i in range(10): 
    save_dir = dir_ + '{}.jpg'.format(i+1)  	 # ‘+’字符串连接
    img.save(save_dir)
3. 编解码
img_bgr = cv2.imread(img_path)
_, s = cv2.imencode('.jpg', img_bgr)
img_bgr_de = cv2.imdecode(s, cv2.IMREAD_COLOR)   # result bgr
img_bgr_mxde = mx.image.imdecode(s).asnumpy()	 # result rgb


header = mx.recordio.IRHeader(0, 4, 2574, 0)	 # flag,label,id,id2
with open(img_path, 'rb') as fin:
	img = fin.read()
s = mx.recordio.pack(header, img)
# header, im_str = mx.recordio.unpack(s)	
_, im1 = mx.recordio.unpack_img(s)          	 # im1 equals to img_bgr

s1 = mx.recordio.pack_img(header, img_bgr)  	 # pack_img: cv2.imencode + pack
header, im2 = mx.recordio.unpack_img(s1)    	 # im2 approximately equals to img_bgr
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值