基于python-opencv3的图像显示和保存操作

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 和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)