import cv2 as cv
import numpy as np #導入庫
print("-------------------------------")
image = cv.imread("D:/1.jpeg") #寫入圖像
cv.imshow("image",image) #顯示
cv.waitKey() #等待
cv.destroyAllWindows() #關閉所有窗口
cv.imwrite("D:\\2.jpeg",image) #保存圖像
首先要導入cv2 和 numpy函數庫,第四行的cv.imread()函數用於寫入一個圖像,imred()函數原型Mat imread(const String& filename,int flags = IMREAD_COLOR);
返回Mat對象,第一個參數是文件的絕對路徑,但並不是支持所有文件對象,它支持的文件如下:
l Windows bitmaps - *.bmp, *.dib (always supported)
l JPEG files - *.jpeg, *.jpg, *.jpe (see the Notes section)
l JPEG 2000 files - *.jp2 (see the Notes section)
l Portable Network Graphics - *.png (see the Notes section)
l WebP - *.webp (see the Notes section)
l Portable image format - *.pbm, *.pgm, *.ppm *.pxm, *.pnm (always supported)
l Sun rasters - *.sr, *.ras (always supported)
l TIFF files - *.tiff, *.tif (see the Notes section)
l OpenEXR Image files - *.exr (see the Notes section)
l Radiance HDR - *.hdr, *.pic (always supported)
l Raster and Vector geospatial data supported by Gdal (see the Notes section)
需要注意的是函數並不是靠識別后綴名,而是靠識別內容的編碼。
其實,我們生活中常用的圖像格式都是可以識別的,所以基本不用擔心這個問題。
第二個參數可以將原圖像進行一定的轉換,此參數很重要,不要輕易設置,默認是IMREAD_LOAD_GDAL 即使用gdal驅動程序加載圖像,常用的有以下幾種:
l IMREAD_UNCHANGED 加載原圖,否則可能會被剪裁
l IMREAD_GRAYSCALE 加載單通道灰度圖像
l IMREAD_COLOR 加載三通道BGR圖像
其他的基本不會用到,也就不再贅述。
下面一行cv.imshow()是顯示圖像,其參數列表(“圖像名”,圖像),
Cv.waitKey()是等待函數,沒有這個函數,會立刻退出,看不到圖像,
參數列表(【delay】):delay=0(無限等待),delay>0(等待delayms),delay<0(等待任意鍵單擊)
Cv.destroyAllWindows()是在運行完程序后關閉所有的窗口,這個是不必須的,但為了好的編程習慣應該這么做,。
最后,cv.imwrite(),則是保存圖像了,其參數(路徑名,圖像名),即把想要保存的圖像保存到指定的路徑里(例如“D:/Ambitio/demo.jpeg”即把圖像保存到D的Ambitio文件夾中,名字為demo,格式為jpeg)