【數字圖像處理】OpenCV中cv2.imread()與PIL中Image.open()的差別


cv2.imread()與PIL中Image.open()兩個函數都是用來讀取圖像,但是在使用過程存在一些差別

1. 首先,從導入庫方面看:

# opencv-python
import cv2

# PIL
from PIL import Image

2. 讀取圖像

# opencv-python
img = cv2.imread('' ---.jpg'')
img = cv2.imread('' ---.jpg'', flages=cv2.IMREAD_GRAYSCALE)     # flags是可選讀入模式,如灰度圖等,默認為None

# PIL
img = Image.open("---.jpg")
img = Image.open("---.jpg", mode=‘r’ ) # mode只能並且默認是‘r’,未查閱到相關資料,暫時不清楚具體代表什么。

值得注意的是,在文檔中對Image.open()函數的描述如下:

   Opens and identifies the given image file.

    This is a lazy operation; this function identifies the file, but
    the file remains open and the actual image data is not read from
    the file until you try to process the data (or call the
    :py:meth:`~PIL.Image.Image.load` method).  See
    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.

Image.open()函數只是保持了圖像被讀取的狀態,但是圖像的真實數據並未被讀取,因此如果對需要操作圖像每個元素,如輸出某個像素的RGB值等,需要執行對象的load()方法讀取數據。具體如下:

img = Image.open("lena.jpg")
img = img.load()
print(img[0,0])
# result:(255, 201, 166)

3. 默認讀入圖像通道

  對於Image.open()函數默認真彩圖像讀取通道順序為RGB,而cv2.imread()則是BGR。同時,當圖像格式為RGBA時,Image.open(‘---.jpg’)讀取的格式為RGBA(其中A表示圖像的alpha通道,即RGBA共四個通道),而cv2.imread('---.jpg')讀取的格式是BGR,只有三個通道。

(1)

    import cv2
    from PIL import Image
    img = cv2.imread(r"F:\DailyPractice\AffectiveComputing\ck+_dataset\1_17_0.png")
    b, g, r = cv2.split(img)
    img = Image.open(r"F:\DailyPractice\AffectiveComputing\ck+_dataset\1_17_0.png")
    print(img.mode)

結果如下:

RGBA

(2)

    import cv2
    from PIL import Image
    img = cv2.imread(r"----.jpg")
    b, g, r, _ = cv2.split(img)
    print(img)
    img = Image.open(r"----.jpg"")
    print(img.mode)

報錯信息如下:

Traceback (most recent call last):
  File "(此處為當前運行腳本名稱及路徑,已被刪除)", line 122, in <module>
    b, g, r, _ = cv2.split(img)
ValueError: not enough values to unpack (expected 4, got 3)

報錯提示 cv2.split(img)只返回三個返回參數,但是‘=’左邊卻有四個接收變量。而(1)是正確的,故 cv2.imread(r"----.jpg")對於RGBA圖像只讀取了BGR三個通道。

 

參考文獻

【1】https://www.cnblogs.com/lyrichu/p/9124504.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM