使用Python在 OpenCV 中读取图像
先决条件: OpenCV 基础
在本文中,我们将尝试使用 OpenCV(开源计算机视觉)打开图像。要在Python中使用 OpenCV 库,我们需要安装这些库作为先决条件:
- Numpy 库(必需,因为 OpenCV 在后台使用它)。
- OpenCVPython
要安装这些库,我们需要在 cmd 中运行这些 pip 命令:
pip install opencv-python
pip install numpy
pip install matplotlib
使用 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.
下面的代码是使用 OpenCV 和 matplotlib 库函数读取图像和在屏幕上显示图像的实现。示例 #1(使用 OpenCV):
使用的图像:
Python3
# Python code to read image
import cv2
# To read image from disk, we use
# cv2.imread function, in below method,
img = cv2.imread("geeksforgeeks.png", cv2.IMREAD_COLOR)
# Creating GUI window to display an image on screen
# first Parameter is windows title (should be in string format)
# Second Parameter is image array
cv2.imshow("Cute Kitens", img)
# To hold the window on screen, we use cv2.waitKey method
# Once it detected the close input, it will release the control
# To the next line
# First Parameter is for holding screen for specified milliseconds
# It should be positive integer. If 0 pass an parameter, then it will
# hold the screen until user close it.
cv2.waitKey(0)
# It is for removing/deleting created GUI window from screen
# and memory
cv2.destroyAllWindows()
Python
# Python program to explain cv2.imread() method
# importing cv2
import cv2
# path
path = r'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)
输出:
示例 #2:以 grascale 模式打开
Python
# Python program to explain cv2.imread() method
# importing cv2
import cv2
# path
path = r'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)
输出 :