一、圖像讀取
API接口
cv2.imread(<str>path, <int>mode)
參數1 path: 圖像的相對路徑或者絕對路徑
參數2 mode: 讀取方式, 分為三種方式
- cv2.IMREAD_COLOR: 以彩色模式讀取(預設)
- cv2.IMREAD_GRAYSCALE: 以灰色圖模式讀取
- cv2.IMREAD_UNCHANGED: 加載圖像包含alpha通道
- 這三個參數可以分别用 1、0、-1 簡化表示
代碼示例
import cv2
# 加載彩色圖像
img = cv2.imread("./test.jpg")
img = cv2.imread("./test.jpg", 1)
# 加載灰階圖像
img = cv2.imread("./test.jpg", 0)
# 帶alpha加載圖像
img = cv2.imread("./test.jpg", -1)
二、圖像顯示
API接口
cv2.imshow(<str>title, <numpy.ndarray>image)
參數1 title: 圖像顯示視窗的标題名稱
參數2 image: 要顯示的圖像,資料類型為 numpy.ndarray
cv2.waitKey(<int>num) 監聽鍵盤函數
參數1 num:圖像停頓的毫秒數,如果為0,該函數将無限時間等待鍵盤鍵入
cv2.destroyAllWindows()
清楚所有的圖像顯示的視窗
cv2.destroyWindow(<str>title)
參數1 tiltle: 清楚指定title的顯示視窗
代碼示範
import cv2
img = imread("./test.jpg")
# 顯示圖像
cv2.imshow("IMG-1", img)
cv2.imshow("IMG-2", img)
# 監聽鍵盤
cv2.waitKey(20)
key_str = str(cv2.waitKey(0))
if key_str == "yes":
print(key_str)
# 删除指定顯示視窗
cv2.destroyWindow("IMG-2")
# 删除所有顯示視窗
cv2.destroyAllWindows()
三、圖像儲存
API接口
cv2.imwrite(<str>path, <numpy.ndarray>image)
參數1 path: 圖像儲存路徑
參數2 image: 要儲存的圖像
代碼示範
import cv2
img = cv2.imread("test.jpg")
# 儲存圖像
cv2.imwrite("test-save.jpg", img)