如何使用Python在OpenCV中读取图像?代码实现

2021年4月8日17:38:07 发表评论 782 次浏览

先决条件:OpenCV基础

在本文中, 我们将尝试使用OpenCV(开放源计算机视觉)打开图像。一些外部库(例如numpy和matplotlib)也将用于完成我们的任务。

为此, 需要安装一些外部库:

pip install opencv-python
pip install numpy
pip install matplotlib

输入图片:

使用Python在OpenCV中读取图像1

Example#1(使用Numpy):

# Python code to reading an image using OpenCV
import numpy as np
import cv2
  
# You can give path to the
# image as first argument
img = cv2.imread( 'cc.jpg' , 0 )
  
# will show the image in a window
cv2.imshow( 'image' , img)
k = cv2.waitKey( 0 ) & 0xFF
  
# wait for ESC key to exit
if k = = 27 : 
     cv2.destroyAllWindows()
      
# wait for 's' key to save and exit
elif k = = ord ( 's' ): 
     cv2.imwrite( 'messigray.png' , img)
     cv2.destroyAllWindows()

Example#2(使用Matplotlib):

# Python code to reading an image using OpenCV
import cv2
import numpy as np
import matplotlib.pyplot as plt
  
img = cv2.imread( 'photo.jpg' , cv2.IMREAD_GRAYSCALE)
  
cv2.imshow( 'image' , img)
cv2.waitKey( 0 )
cv2.destoryAllWindows()

输出:

使用Python在OpenCV中读取图像2

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: