PIL,cv2,plt的使用與區別
- 1 比較三者的打開圖片、顯示圖片、打開的圖片的型別
- 2 影像型別的轉換(PIL與numpy)
1 比較三者的打開圖片、顯示圖片、打開的圖片的型別
from PIL import Image
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 比較三者的打開圖片、顯示圖片、打開圖片的型別
# ************PIL************
PIL_img = Image.open('D:/images/Rimi.jpg')
print(type(PIL_img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
print(PIL_img.size) # (1152, 720) (w,h)
print(np.array(PIL_img).shape) # (720, 1152, 3) (h,w,c)
PIL_img.show()
# ************cv2************
cv2_img = cv2.imread('D:/images/Rimi.jpg')
print(type(cv2_img)) # <class 'numpy.ndarray'>
print(cv2_img.shape) # (720, 1152, 3) (h,w,c)
cv2.imshow('cv2', cv2_img)
# cv2.waitKey()
# ************plt***********
plt_img = plt.imread('D:/images/Rimi.jpg')
print(type(plt_img)) # <class 'numpy.ndarray'>
print(plt_img.shape) # (720, 1152, 3) (h,w,c)
plt.imshow(plt_img) # PIL_img也可以顯示
plt.show()
可以看到cv2與plt打開的圖片型別都是numpy,而PIL是自己獨自的型別,當然這三者可以互相轉換,(注意:plt可以顯示numpy型別的影像,也可以顯示PIL型別的)
且PIL打開影像的shape為(w,h),而cv2與plt打開rgb影像都是(h,w,c),將PIL格式影像轉為numpy后,其格式也變為(h,w,c)

2 影像型別的轉換(PIL與numpy)
# PIL轉numpy
img_trans = np.array(PIL_img)
print(type(img_trans)) # <class 'numpy.ndarray'>
# numpy轉PIL
img_trans = Image.fromarray(cv2_img)
print(type(img_trans)) # <class 'PIL.Image.Image'>```
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/297387.html
標籤:其他
