Python OpenCV | cv2.imread() 方法
OpenCV-Python是一个Python绑定库,旨在解决计算机视觉问题。
cv2.imread()
方法从指定文件加载图像。如果无法读取图像(由于缺少文件、权限不正确、格式不受支持或无效),则此方法返回一个空矩阵。
Syntax: cv2.imread(path, flag)
Parameters:
path: A string representing the path of the image to be read.
flag: It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR
Return Value: This method returns an image that is loaded from the specified file.
注意:图像应在工作目录中或应给出图像的完整路径。
所有三种类型的标志如下所述:
cv2.IMREAD_COLOR: It specifies to load a color image. Any transparency of image will be neglected. It is the default flag. Alternatively, we can pass integer value 1 for this flag.
cv2.IMREAD_GRAYSCALE: It specifies to load an image in grayscale mode. Alternatively, we can pass integer value 0 for this flag.
cv2.IMREAD_UNCHANGED: It specifies to load an image as such including alpha channel. Alternatively, we can pass integer value -1 for this flag.
用于以下所有示例的图像:
示例 #1:使用默认标志
# Python program to explain cv2.imread() method
# importing cv2
import cv2
# path
path = r'C:\Users\Rajnish\Desktop\geeksforgeeks.png'
# Using cv2.imread() method
img = cv2.imread(path)
# Displaying the image
cv2.imshow('image', img)
输出:
示例 #2:
以灰度模式加载图像
# Python program to explain cv2.imread() method
# importing cv2
import cv2
# path
path = r'C:\Users\Rajnish\Desktop\geeksforgeeks.png'
# Using cv2.imread() method
# Using 0 to read image in grayscale mode
img = cv2.imread(path, 0)
# Displaying the image
cv2.imshow('image', img)
输出: