使用OpenCV读写图片

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(),需要给定的参数有:文件名,需要保存的图像。

猜你喜欢

转载自www.cnblogs.com/puheng/p/9228500.html