📜  使用Python在 OpenCV 中读取图像

📅  最后修改于: 2022-05-13 01:54:48.725000             🧑  作者: Mango

使用Python在 OpenCV 中读取图像

先决条件: OpenCV 基础

在本文中,我们将尝试使用 OpenCV(开源计算机视觉)打开图像。要在Python中使用 OpenCV 库,我们需要安装这些库作为先决条件:

  1. Numpy 库(必需,因为 OpenCV 在后台使用它)。
  2. OpenCVPython

要安装这些库,我们需要在 cmd 中运行这些 pip 命令:

pip install opencv-python
pip install numpy
pip install matplotlib

使用 cv2.imread() 方法读取图像。此方法从指定文件加载图像。如果无法读取图像(由于缺少文件、权限不正确、格式不受支持或无效),则此方法返回一个空矩阵。

注意:图像应在工作目录中或应给出图像的完整路径。

所有三种类型的标志如下所述:

下面的代码是使用 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)

输出 :