使用 OpenCV 处理图像和视频
介绍
众所周知,计算机视觉在机器学习和人工智能领域获得了巨大的普及。图像识别技术允许计算机处理比人眼更多的信息,通常更快、更准确,或者只是在人们不参与观看的情况下处理。因此,你可能想知道机器如何学习和解释视觉世界。
在本文中,我将介绍如何使用 Python 的 OpenCV 库开始处理图像和视频。我们将涵盖以下主题:
- 计算机视觉简介
- OpenCV 库及其应用简介
- 如何使用 OpenCV 库处理图像和视频
计算机视觉
它是人工智能和计算机科学的一个领域,训练计算机理解视觉世界。它是机器学习的主要组成部分之一。它处理自然世界的图像(高维数据)。它执行各种任务,例如获取、分析和处理以理解图像并将其转换为数字或符号信息。
当今的计算机视觉算法基于模式识别,通常依赖于卷积神经网络 (CNN)。由于该领域的各种进步,计算机视觉正在蓬勃发展,并且它的受欢迎程度在过去几年中呈指数增长。
计算机视觉的应用范围从缺陷检测到入侵者检测、口罩检测到肿瘤检测、作物监测到植物监测、车辆分类到交通流量分析等。该技术主要应用于零售和制造、交通、媒体、农业、医疗保健、体育、银行、增强现实、家庭安全等。
OpenCV
Python 包含一个名为 OpenCV 的库,用于在计算机视觉领域工作。它是一个开源库,于 1999 年推出。我们可以执行图像处理、图像分析、视频分析等任务。该库主要用 C++ 编写,具有 C++、Python、Java 和 MATLAB 等接口。
应用:
- 2D 和 3D 特征工具包
- 视频/图像搜索检索
- 人脸识别系统
- 手势识别
- 移动机器人
- 对象识别
- 医学影像分析
- 运动追踪
- 增强现实
安装
使用 pip 命令可以轻松安装 OpenCV,如下所示
pip install opencv-python
使用 OpenCV 处理图像
在处理图像时,OpenCV 有许多可以对图像执行的操作。其中,我将讨论:
- 读取图像
- 调整图像大小
- 旋转图像
- 翻转图像
- 重写图像
- 裁剪图像
- 在图像上绘制各种形状
1. 从文件中读取图像
- 使用函数imread()读取图片 (支持BMP、jpeg、tiff、png、便携图片格式等)
- 为了显示我们在上一步中读取的图像,我们使用函数“imshow()”。这个函数的第一个参数是标题,第二个是我们读到的图像。
- waitkey() 函数显示一个窗口几毫秒。毫秒数作为参数传递给函数。如果 0 作为参数传递,它将永远等待,直到按下任何键。
- 最后,destroyAllWindows() 将图像窗口显示后从内存中删除。
例子:
python 代码:
import
cv2
img=cv2.imread(
'img.jpeg')
cv2.imshow(
'Image',img)
cv2.waitKey()
cv2.destroyAllWindows()
输出
2. 调整图像大小:
在图像处理中,经常需要调整图像的大小。OpenCV 为我们提供了几种轻松重新缩放图像的方法。让我们通过一个例子来理解。
例子:
img2=cv2.resize(img,(
400,
400))
#resize by a fraction of original size
img3=cv2.resize(img,(
0,
0),fx=
0.5,fy=
0.6)
#using INTER_AREA to shrink the image
img4=cv2.resize(img,(
600,
700),interpolation=cv2.INTER_AREA)
3. 旋转图像
使用 OpenCV 旋转图像的语法是
M=cv2.getRotationMatrix2D(center, angle,scale)
然后我们使用方法
cv2.wrapAffine(src,M, (h,w))
让我们通过一个例子来深入了解:
例子:
#calculate height and width to get center
#rotate by 90 degrees
#rotate by 180 degrees
#rotate by 270 degrees
(h,w)=img.shape[:
2]
center=(w/
2,h/
2)
#rotate by 90 degrees
M = cv2.getRotationMatrix2D(center,
90,
1.0)
img90 = cv2.warpAffine(img, M, (h, w))
#rotate by 180 degrees
M = cv2.getRotationMatrix2D(center,
180,
1.0)
img180 = cv2.warpAffine(img, M, (h, w))
#rotate by 270 degrees
M = cv2.getRotationMatrix2D(center,
270,
1.0)
img270 = cv2.warpAffine(img, M, (h, w))
4. 翻转图像:
要翻转图像,我们使用函数 cv2.flip() 并传递参数,即图像和翻转代码(水平或垂直)
例子:
#flip- vertical axes
#flip- horizontal axes
img=cv2.flip(img,
0)
#flip- horizontal axes
img=cv2.flip(img,
1)
5. 重写图像
要将图像重写为新文件,我们使用函数 imwrite() 如下:
cv2.imwrite(
'new_img.jpg',img)
6. 裁剪图像
#crop from top
#crop by specifying height and width
img=img[
0:
100,
0:
100]
#crop by specifying height and width
img=img[
50:
200,
50:
100]
7. 绘制形状
使用 OpenCV,我们可以使用不同的函数在图像上快速绘制各种形状,如圆形、矩形、多边形等。让我们用一个例子来理解:
例子:
#creating a blank image
import
import
#changing the color of the image to green
#Red
import
cv2
as cv2
import
numpy
as np
img=np.zeros((
500,
500,
3),dtype=float)
#changing the color of the image to green
img[:]=
0,
255,
0#Red
img[:]=
0,
0,
255#changing the color of a particular portion
#drawing a rectangle
#draw a circle with filling the color
#drawing a line
#adding text
img[
200:
300,
300:
450]=
0,
255,
0#drawing a rectangle
cv2.rectangle(img,(
100,
100),(
180,
180),color=(
255,
0,
0),thickness=
5)
#draw a circle with filling the color
cv2.circle(img,center=(
100,
300),radius=
60,color=(
0,
255,
0),thickness=
-1)
#drawing a line
cv2.line(img,(
0,
0),(
317,
356),thickness=
3,color=(
0,
255,
0))
#adding text
cv2.putText(img,org=(
50,
50),fontScale=
3,color=(
255,
0,
0)
,thickness=
2,lineType=cv2.LINE_AA,text=
"IMAGES", fontFace=cv2.FONT_HERSHEY_COMPLEX_SMALL)
cv2_imshow(img)
cv2.waitKey(
0)
使用 OpenCV 处理视频
视频是帧序列或图像序列。图像通常采用 BGR(蓝、绿、红)的形式。每个像素的值都在 0-255 之间。要开始使用 OpenCV 处理视频,我们使用以下函数:
Cv2.VideoCapture():它建立与视频的连接。它带有一个参数,该参数指示是使用内置摄像头还是附加摄像头。值“0”表示内置摄像头。
Cap.read():这个方法可以让我们得到一个帧。
Cv2.cvtColor():允许你更改图像使用的颜色模型。这包括从 BGR 转换为 RGB 和灰度。
在处理视频方面,在本文中,我们将学习
- 如何捕获视频帧的不同属性
- 读取视频文件
- 写视频
1. 捕获视频帧的属性:
让我们看几个捕获视频属性的示例。
- 要捕获帧形状:
frame.shape
(
2160,
3840,
3)
plt.imshow(frame)
plt.show()
- 要更改框架的颜色,我们使用函数 cv2.cvtColor(),如下所示:
#changing the color of the frame
plt.show()
plt.imshow(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY))
- 为了捕捉视频,我们使用函数 cv2.VideoCapture()
cap=cv2.VideoCapture(
'/content/video.mp4')
cap.read()
- 要获取框架的高度,我们使用 cap.get() 函数如下:
#height
cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
- 为了获得框架的宽度,我们使用:
#width
cap.get(cv2.CAP_PROP_FRAME_WIDTH)
- 要获取帧数,我们使用函数 cap.get() 如下:
#number of frames
cap.get(cv2.CAP_PROP_FRAME_COUNT)
- 为了获得每秒的帧数,我们使用
#number of frames per sec
cap.get(cv2.CAP_PROP_FPS)
2. 读取视频文件
- 导入 cv2
- 然后我们使用函数 cv2.VideoCapture() 来捕捉视频。
- 接下来,我们循环遍历每一帧并使用函数 cap.read() 读取帧。
- 为了显示每一帧,我们使用方法 cv2.imshow()。
- 最后,我们使用 waitKey() 函数中断循环,当用户按下任意键时,该函数会中断循环。
- destroyAllWindows() 函数将关闭窗口。
例子:
#importing dependencies
import
from
#establish capture
#loop through each frame
while
if
break
#close down everything
import
cv2
from
matplotlib
import pyplot
as plt
#establish capture
cap=cv2.VideoCapture(
'/content/video.mp4')
#loop through each frame
while
(cap.isOpened()):
ret,frame=cap.read()
frame=cv2.resize(frame,(
1200,
700))
cv2.imshow(‘Video’,frame)
if
cv2.waitKey(
10) &
0xFF == ord(
'q'):
break
#close down everything
cap.release()
cv2.destroyALLWindows()
3. 编写视频文件
- 导入 cv2
- 使用函数 cv2.VideoCapture() 捕获视频
- 然后我们使用函数 cv2.VideoWriter 来编写视频。该函数将参数作为
- cv2.VideoWriter(filename, fourcc, fps, framesize)
- filename - 捕获的输入视频文件
- Fourcc - 用于指定视频编解码器的代码
- fps - 每秒帧数
- framesize - 视频框的高度和宽度
- 接下来,我们循环遍历每一帧并使用对象 video_writer 来写入帧。
- 最后,我们使用 waitKey() 函数来打破循环
- 使用函数 destroyAllWindows() 关闭窗口
import
from
for
if
break
cv2
from
google.colab.patches
import cv2_imshow
cap=cv2.VideoCapture(
'/content/video.mp4')
height=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fps=int(cap.get(cv2.CAP_PROP_FPS))
frame_size = (width,height)
video_writer= cv2.VideoWriter(
'/content/output.avi',cv2.VideoWriter_fourcc(
'M',
'J',
'P',
'G'), fps, frame_size)
for
frame_idx
in range(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))):
ret,frame=cap.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
video_writer.write(gray)
if
cv2.waitKey(
10) &
0xFF== ord(
'q'):
break
cap.release()
cv2.destroyALLWindows()
结论
本文帮助你创建了与计算机视觉相关的出色应用程序。希望你现在对以下内容有一个很好的了解:
- 什么是计算机视觉
- OpenCV 库的应用
- 使用 OpenCV 库处理图像
- 使用 OpenCV 库处理视频
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。