OpenCV教程-OpenCV读取和保存图像
整理:python技术迷
OpenCV读取图像
OpenCV允许我们对图像执行多种操作,但为了做到这一点,需要将图像文件读取为输入,然后我们可以对其执行各种操作。OpenCV提供了以下用于读取和写入图像的函数。
OpenCV imread函数
cv2.imread(filename[,flag])
参数:
filename:要加载的文件的名称
flag:该标志指定加载图像的颜色类型:
CV_LOAD_IMAGE_ANYDEPTH - 如果将其设置为标志,当输入具有相应深度时,它将返回16位/32位图像,否则将其转换为8位。
CV_LOAD_IMAGE_COLOR - 如果将其设置为标志,它将始终返回转换后的彩色图像。
CV_LOAD_IMAGE_GRAYSCALE - 如果将其设置为标志,它将始终将图像转换为灰度。
imread()函数返回一个矩阵,如果由于不支持的文件格式、缺少文件、不支持或无效的格式而无法读取图像,则会发生错误。目前支持以下文件格式。
Windows位图 - *.bmp, *.dib JPEG文件 - *.jpeg, *.jpg, *.jpe 可移植网络图形 - *.png 便携式图像格式- *.pbm, *.pgm, *.ppm TIFF文件 - *.tiff, *.tif
注意:对于彩色图像,解码后的图像将以BGR顺序存储通道。
#importing the opencv moduleimport cv2# using imread('path') and 0 denotes read as grayscale imageimg = cv2.imread(r'C:\Users\DEVANSH SHARMA\cat.jpeg',1)#This is using for display the imagecv2.imshow('image',img)cv2.waitKey(3) # This is necessary to be required so that the image doesn't close immediately.#It will run continuously until the key press.cv2.destroyAllWindows()
输出:它将显示以下图像。
👉点击领取:最全Python资料合集
OpenCV保存图像
cv2.imwrite(filename, img[,params])
参数:
filename- 要加载的文件的名称
image- 要保存的图像。
params- 当前支持以下参数:
对于JPEG,质量可以从0到100。默认值为95。
对于PNG,质量可以是0到9的压缩级别。默认值为1。
对于PPM、PGM或PBM,它可以是0或1的二进制格式标志。默认值为1。
import cv2# read image as grey scaleimg = cv2.imread(r'C:\Users\DEVANSH SHARMA\cat.jpeg', 1)# save imagestatus = cv2.imwrite(r'C:\Users\DEVANSH SHARMA\cat.jpeg', 0, img)print("Image written to file-system : ", status)
Image written to file-system : True
如果imwrite()函数返回True,则表示文件已成功写入指定文件。
热门推荐