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))
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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章