1、 OpenCV中的cv2.imread()函數和cv2.imwrite()支持各種靜態圖片格式,如BMP、JPG、PNG、tiff等。使用函數cv2.imread() 讀入圖像。這幅圖像應該在此程序的工作路徑,或者給函數提供完整路徑,第二個參數是要告訴函數應該如何讀取這幅圖片。
OpenCV官方文檔給出的第二個參數有如下類型:
IMREAD_UNCHANGED Python: cv.IMREAD_UNCHANGED |
If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). |
IMREAD_GRAYSCALE Python: cv.IMREAD_GRAYSCALE |
If set, always convert image to the single channel grayscale image. |
IMREAD_COLOR Python: cv.IMREAD_COLOR |
If set, always convert image to the 3 channel BGR color image. |
IMREAD_ANYDEPTH Python: cv.IMREAD_ANYDEPTH |
If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. |
IMREAD_ANYCOLOR Python: cv.IMREAD_ANYCOLOR |
If set, the image is read in any possible color format. |
IMREAD_LOAD_GDAL Python: cv.IMREAD_LOAD_GDAL |
If set, use the gdal driver for loading the image. |
IMREAD_REDUCED_GRAYSCALE_2 Python: cv.IMREAD_REDUCED_GRAYSCALE_2 |
If set, always convert image to the single channel grayscale image and the image size reduced 1/2. |
IMREAD_REDUCED_COLOR_2 Python: cv.IMREAD_REDUCED_COLOR_2 |
If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. |
IMREAD_REDUCED_GRAYSCALE_4 Python: cv.IMREAD_REDUCED_GRAYSCALE_4 |
If set, always convert image to the single channel grayscale image and the image size reduced 1/4. |
IMREAD_REDUCED_COLOR_4 Python: cv.IMREAD_REDUCED_COLOR_4 |
If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. |
IMREAD_REDUCED_GRAYSCALE_8 Python: cv.IMREAD_REDUCED_GRAYSCALE_8 |
If set, always convert image to the single channel grayscale image and the image size reduced 1/8. |
IMREAD_REDUCED_COLOR_8 Python: cv.IMREAD_REDUCED_COLOR_8 |
If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. |
IMREAD_IGNORE_ORIENTATION Python: cv.IMREAD_IGNORE_ORIENTATION |
If set, do not rotate the image according to EXIF's orientation flag. |
2、 一個OpenCV圖像是一個.array類型的二維或三維數組,可以用表達式訪問這些值,如image[0,0]或image[0,0,0]。使用numpy.array方法來訪問數組的元素通常會更快,使用.item()方法可以很快的訪問數組的元素,該方法有3個參數:x,y,(x,y)位置的數組索引例如:item(150,200,0)表示位置為(150,200)處的第0個通道的像素點,使用.itemset()方法可以用來設置某個像素點的值,其參數為一個三元組和一個數值,用來指定待設定的像素點的位置以及設定值,例如:itemset((150,200,0),255)。
3、 顯示一張圖片:使用.imshow()方法可以將一張圖片顯示出來,需要給定的參數有兩個,第一個參數是顯示窗口的名稱,第二個參數是待顯示的圖片名稱。可以創建多個窗口,但是他們的名稱要不同。通常在顯示圖片的命令之后會有這樣兩行語句:cv2.waitKey(),cv2.destroyAllwindows。第一行語句使用了cv2.waitKey()函數,括號內參數的值若給定,則圖片會顯示給定值的時長,單位為毫秒,若設置為0,則一直顯示直到接收到來自鍵盤的輸入;若未給定,則顯示圖片后,窗口馬上銷毀。第二行語句是銷毀所有建立的窗口。你也可以先創建一個窗口,之后再加載圖像。這種情況下,你可以決定窗口是否可以調整大小。使用到的函數是cv2.namedWindow()。初始設定函數標簽是cv2.WINDOW_AUTOSIZE。但是如果你把標簽改成cv2.WINDOW_NORMAL,你就可以調整窗口大小了。當圖像維度太大,或者要添加軌跡條時,調整窗口大小將會很有用。
例如:
cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows()
4、 保存圖像:使用cv2.imwrite(),需要給定的參數有:文件名,需要保存的圖像。