OpenCV Python影像讀取與儲存程式
OpenCV-python 是一個基於Python的開源計算機視覺庫,用於處理影像和影片,進行人臉和物體檢測。它是Python中常用的影像處理庫之一,使用Python NumPy庫,所有影像陣列都表示為ndarray型別。
使用pip安裝OpenCV
Pip install opencv-python
OpenCV需要NumPy庫,需要確保NumPy庫也已安裝。Python OpenCV模組提供cv2.imread()和cv2.imwrite()函式來讀取/載入和寫入/儲存影像檔案。
本文將介紹如何使用Python OpenCV模組讀取和儲存影像檔案。
cv2.imread()函式
cv2.imread()函式讀取/載入影像並將其儲存為NumPy陣列。
語法
Cv2.imread(filename[, flags])
引數
檔名: 要載入的檔案的名稱/路徑。
標誌: 可以取imreadModes值的標誌,指定載入影像的顏色型別。
返回值
該方法返回一個NumPy陣列。如果無法讀取影像(由於檔案丟失、許可權不足或格式不支援/無效),則此函式將返回空矩陣而不是生成錯誤。
該函式透過內容而不是副檔名來確定影像的型別。
支援的檔案格式
Windows點陣圖: *.bmp, *.dib
JPEG檔案: *.jpeg, *.jpg, *.jpe
JPEG 2000檔案: *.jp2
行動式網路圖形: *.png
WebP: *.webp
行動式影像格式: *.pbm, *.pgm, *.ppm *.pxm, *.pnm
Sun光柵: *.sr, *.ras
OpenEXR影像檔案: *.exr
Radiance HDR: *.hdr, *.pic
注意: GDAL支援光柵和向量地理空間資料
讀取影像的演算法
匯入cv2模組。
使用cv2.imread()方法讀取影像。
使用cv2.imshow()方法在視窗中顯示影像。
使用cv2.waitKey(0)方法設定輸出視窗的計時器。
最後,使用cv2.destroyAllWindows()方法關閉輸出視窗。
示例
讓我們以影像作為輸入。
#importing the opencv module import cv2 # read image using imread('path') and 0 denotes read as grayscale image img = cv2.imread('input.jpg',0) # display image cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows()
輸出
示例
imread()函式將彩色影像儲存在行(高度)x列(寬度)x顏色(3)的3D ndarray中。讓我們以彩色影像作為輸入,並使用imread()函式讀取它。
#importing the opencv module import cv2 # read image img = cv2.imread('logo.png') # display image cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() print('Type:',type(img)) print('Shape:',img.shape) print('datatype',img.dtype)
輸出
Type: <class 'numpy.ndarray'>Shape: (225, 225, 3) datatype uint8
影像物件img儲存了形狀為(225, 225, 3)的3維NumPy陣列。
cv2.imwrite()函式
cv2.imwrite()函式以指定的名稱儲存影像。檔名副檔名和位置也從函式的第一個引數中選擇。
此函式返回布林值,如果影像成功寫入,則返回True,否則返回False。如果指定了不受支援的影像格式,則影像將轉換為8位無符號(CV_8U)並以這種方式儲存。
以下是此函式的語法:
Cv2.imwrite(filename, img[, params])
其中:
檔名: 要儲存檔案的名稱/路徑。
img: 它採用ndarray的值來儲存影像。
params: 編碼為對的格式特定引數列表。
示例
在這個例子中,我們將使用(100,100,3)形狀的零陣列儲存影像。
#import the numpay and opencv modules import numpy as np import cv2 # create a 3-d numpy array blank_image2 = np.zeros((100,100,3), dtype=np.uint8) # save or create an image cv2.imwrite("written_image.jpg", blank_image2)
輸出
True
該函式返回布林值True,這表示檔案已成功寫入/儲存,指定名稱為written_image.jpg的空白影像也顯示在上面的輸出塊中。
示例
在這個例子中,我們將從Image資料夾讀取lenna.png影像,然後使用params引數以最高的質量重新寫入它。
矩陣 [cv2.IMWRITE_JPEG_QUALITY, 100] 表示最高質量。而0表示最低質量,預設值為95。
#importing the opencv module import cv2 # read image using imread('path') and 0 denotes read as grayscale image img = cv2.imread('input.jpg',1) cv2.imshow('Input image',img) cv2.waitKey(0) cv2.destroyAllWindows() print('Type:',type(img)) status = cv2.imwrite('Images/Output_lenna_opencv_red_high.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 100]) print('Status:', status)
輸入
Type: <class 'numpy.ndarray'Status: True Details of the
img物件的型別是ndarray。imwrite()函式成功地將影像Output_lenna_opencv_red_high.jpg儲存到Images資料夾中。