栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[深度学习]Part2 Python学习进阶Ch24图像处理OpenCV——【DeepBlue学习笔记】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[深度学习]Part2 Python学习进阶Ch24图像处理OpenCV——【DeepBlue学习笔记】

本文仅供学习使用

Python高级——Ch24图像处理OpenCV
  • 24. 图像处理OpenCV
    • 23.1 图像读取、显示、保存
      • 23.1.1 图像的基本操作
      • 23.1.2 摄像头/视频读取、写入
      • 23.1.3 简单实例应用


24. 图像处理OpenCV

OpenCV(Open Source Computer Vision Library)是一个基于(开源免费)发行的跨平台计算机视觉库,可以运行在Linux、Windows、Android、ios等操作系统上,它轻量级而且高效—由一系列C函数和少量C++类构成,同时提供了Python、Ruby、MATLAB等语言的接口,实现了图像处理和计算机视觉方面的诸多通用算法。

参考网址
http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_tutorials.html
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html
http://docs.opencv.org/2.4/genindex.html

OpenCV模块简介:
import cv2
【core】–核心功能模块,包含OpenCV基本数据结构和绘图函数等
【imgproc】–Image/Process,包含滤波、几何变换、直方图相关、 特征检测、运动分析和形状描述等
【highgui】–高层图形用户界面,包含媒体输入输出、视频捕捉、 图像和视频的编码解码、图形交互界面接口等
【calib3d】–Calibration和3D,相机标定和三维重建相关
【contrib】–新增人脸识别、立体匹配、人工视网膜模型等技术
【features2d】–2D功能框架,主要包含特征检测和描述及接口
【flann】–快速最近邻搜索算法和聚类
【gpu】–运用GPU加速的计算机视觉模块
【legacy】–(弃用)包含运动分析、平面细分、描述符提取等
【ml】–Machine Learning,机器学习模块
【objdetect】–目标检测模块(级联分类器和SVM)
【photo】–包含图像修复和图像去噪两部分
【stitching】–图像拼接模块
【……】

OpenCV安装
pip install opencv-python

import cv2
print(cv2.__version__)

一个简单的程序

import cv2
#图像的基本操作
img = cv2.imread('datas/fengjing.jpg')

cv2.imshow('img',img)

k = cv2.waitKey(0)  # 等待按键
print(k)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
    cv2.imwrite('datas/messigray.png',img)
    cv2.destroyAllWindows()  # 销毁所有窗口
23.1 图像读取、显示、保存

OpenCV图像处理系统一般组成:

23.1.1 图像的基本操作

图像读取:cv2.imread()
窗口创建:cv2.namedWindow()
图像显示:cv2.imshow()
图像保存:cv2.imwrite()
资源释放:cv2.destroyWindow()

import cv2
#图像的基本操作

img = cv2.imread('datas/fengjing.jpg')  # 读取图像
cv2.imshow('img',img)  # 显示原图

hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)  # 转为HSV图像
cv2.namedWindow("hsv",cv2.WINDOW_AUTOSIZE)  # 创建hsv窗口

cv2.imshow("hsv",hsv_img)  # 显示hsv图像
cv2.imwrite("hsv.jpg",hsv_img)  # 保存hsv图像
cv2.waitKey(0)  # 等待按键按下
cv2.destroyAllWindows()  # 销毁所有窗口

cv2.imread(filename, [flags])
第一个参数,需要填入图片路径名,支持如下格式:
· Windows bitmaps -*.bmp,*.dib(always supported)
· JPEG files-*.jpeg,*.jng,*.jpe (see the Motes section)
· JPEG 2000 files -*.jp2(see the Ntes section)
· Portable Network Graphics -*png (see the Motes section)
· Portable image format-*.pbm,*.pgm,*.ppm (always supported)
· Sun rasters -*.sr,*.ras(always supported)
· TIFF files -*.tiff,*.tif(see the Notes section)
注意路径格式用或/,同时路径中不要有中文
第二个参数,指定加载图像的颜色类型 ,默认为1:
cv2.IMREAD cOLOR # 读入彩色图像,透明度被忽略,对应宏定义为1(默认参数)
cv2.IMREAD GRAYSCALE # 以灰度模式读入图像,对应宏定义为0
cv2.IMREAD UNCHANGED # 读入图像包含alpha通道,对应宏定义为-1
警告∶就算图像的路径是错的,OpenCV 也不会提醒你的,但是当你使用命令print img时得到的结果是None。

通过判断img是否为None来避免异常发生

import cv2

img0 = cv2.imread('datas/fengjing.jpg', cv2.IMREAD_GRAYSCALE)#0
if img0 is None:
    print('imgread is error')
else:
    print('imgread is ok')
    cv2.imshow('img0',img0)
    print(img0.shape)  # (546,820)  一个通道
    
img1 = cv2.imread('datas/fengjing.jpg', 1)#0
if img0 is None:
    print('imgread is error')
else:
    print('imgread is ok')
    cv2.imshow('img1',img1)
    print(img1.shape)  # (546,820,3)  三个通道

#  不同通道下的灰度图——RGB
img1_0 = img1[..., 0]
img1_1 = img1[..., 1]
img1_2 = img1[..., 2]
cv2.imshow('img1_0',img1_0)
cv2.imshow('img1_1',img1_1)
cv2.imshow('img1_2',img1_2)
cv2.waitKey(0)

namedWindow(winnname, [flags])
第一个参数,表示窗口名称,传入字符串即可
第二个参数,窗口显示方式,取值如下:
cv2.WINDOW NORMAL # 正常大小显示,用户可以改变窗口大小
cv2.WINDow AUTOSIZE # 根据图像大小自动调整,用户不能手动改变窗口大小

imshow(winnname, mat)
第一个参数,设置需要显示的窗口名称
第二个参数,填写需要显示的图像

imwrite(filename, img, [params])
第一个参数,设置保存的文件名,需填写后缀,如"1.bmp"
第二个参数,要保存的Mat类型图像数据
第三个参数,表示特定格式保存的参数编码,一般采用默认值不填写
对于JPEG,其表示的是图像的质量,用0~100的整数表示,默认为95
对于PNG,第三个参数表示的是压缩级别,从0到9,压缩级别越高,图像尺寸越小,默认级别为3

waitKey([delay])
第一个参数,如果delay>0, 表示等待delay毫秒之后结束; 如果delay=0, 表示无限等待,直到有按键按下结束
返回值为对应按下按键的ASCII码值, 如Esc的ASCII码为27

k = cv2.waitKey(0)
print(k)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
    cv2.imwrite('datas/messigray.png',img)
    cv2.destroyAllWindows()

destroyWindow(winname) / destroyAllWindow()
cv2.destroyWindow()销毁指定窗口,参数填窗口名称
cv2.destroyAllWindows()销毁所有打开的GUI窗口

img is None 判断图像是否为空(读取是否成功)
img.shape[0] 获取图像行数(高度)
img.shape[1] 获取图像列数(宽度)
img.shape[2] 获取图像通道数
img.size 获取总的像素个数(宽度x高度x通道数)
img.dtype 获取图像的数据类型

import cv2
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('datas/fengjing.jpg')
#cv2显示 BGR
cv2.imshow('cv2', img)
cv2.waitKey(0)
#matlab显示 RGB
plt.imshow(img)
plt.show()
#顺序调整
plt.imshow(img[:,:,::-1])
plt.show()

# Release everything if job is finished
cv2.destroyAllWindows()
23.1.2 摄像头/视频读取、写入

VideoCapture类: OpenCV2.x及以上版本新增VideoCapture类,提供了从摄像机或视频文件捕获视频的C++接口。
VideoCapture类三种构造函数方法:

Python: cv2.VideoCapture() →
Python:cv2.VideoCapture(filename) →
Python:ev2.VideoCapture(device) →
参数说明:
参数filename表示输入视频文件的路径及名称
device表示打开摄像头索引号

取帧方法:
Python: cv2.VideoCapture.read([image]) → retval, image

import cv2

# 视频的基本操作 —— 单帧图片 
cap = cv2.VideoCapture(0)  # device
ret, frame = cap.read()  # ret是否能取到帧,frame帧图片(ndarray)
cv2.imshow('frame', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2

# 视频的基本操作  —— 视频  
cap = cv2.VideoCapture(0)  # device
ret, frame = cap.read()  # ret是否能取到帧,frame帧图片(ndarray)
count = 0
while True:
    count += 1
    ret, frame = cap.read()
    if not ret:
        break
    if count > 240:
        cap.release()
    # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#颜色空间转换
    cv2.imshow('frame', frame)
    cv2.waitKey(1)

VideoCapture类常用函数功能:

cv2.VideoCapture.open(filename) → retval
cv2.VideoCapture.open(device) → retval
open()—打开视频文件或者摄像头

#cap = cv2.VideoCapture(0)  #device
cap = cv2.VideoCapture('datas/vedioplay.mp4') #filename
# cap = cv2.VideoCapture()
# cap.open('datas/vedioplay.mp4')

cv2.VideoCapture.isOpened()→ retval
isOpened()–判断读取视频文件是否正确,正确返回true

print(cap.isOpened())

cv2.VideoCapture.release() → None
release()—关闭视频流文件

cv2.VideoCapture.grab()→ retval
grab()—抓取下一帧的视频文件或设备

cv2.VideoCapture.retrieve([image[,channel]]) → retval, image → retval, image
retrieve()—解码并返回视频帧

cv2.VideoCapture.get(propId) → retval
get()—返回指定视频类的相关参数信息

cv2.VideoCapture.set(propId,value) → retval
set()—设置类信息的一个属性

# 视频属性
import cv2
cap = cv2.VideoCapture('datas/vedioplay.mp4')

# 帧率
fps = cap.get(cv2.CAP_PROP_FPS)  # 25.0
print("Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps))

# 总共有多少帧
num_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
print('共有', num_frames, '帧')
#
frame_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
print('高:', frame_height, '宽:', frame_width)

#FRAME_NOW = cap.get(cv2.CAP_PROP_POS_FRAMES)  # 第0帧
#print('当前帧数', FRAME_NOW)  # 当前帧数 0.0

# Release everything if job is finished
cap.release()

读取视频:
说明:视频读取本质上就是读取图像,因为视频是由一帧一帧图像组成的。

  1. 读取视频的两种方法:
# 1
cap = cv2.VideoCapture('datas/vedioplay.mp4') #filename

# 2
cap = cv2.VideoCapture()
cap.open('datas/vedioplay.mp4')
  1. 循环显示每一帧:
while True:
    ret, frame = cap.read()
    if not ret:  # ret == False
        break
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 颜色空间转换
    cv2.imshow('frame',  hsv_frame)
    if cv2.waitKey(10) & 0xFF == 27:
        cv2.imwrite('1.bmp', hsv_frame)
        print('1')

几点说明:

  1. 打开的视频可以是本地视频如:cv2.VideoCapture cap("1.avi");
    也可以是网络视频如:cv2.VideoCapture cap("http://www.laganiere.name/bike.avi");

  2. 读取视频一定要加异常判断
    ① 打开视频失败(各种原因)
    ② 取帧失败异常(程序结尾判断)
    ex1:if(cap.isopened())∶#检查打开是否成功
    ex2:

ret,frame = cap.read()
# if(frame is None)∶# 判断当前帧是否为空
if ret==False∶# 判断取帧是否失败
	break

写入视频:

  1. VideoWriter:
    Opencv提供VideoWriter类写视频文件,类的构造函数可以指定文件名、播放帧率、帧尺寸、是否创建彩色视频。

cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]) →
· filename - Name of the output video file.
· fourcc - 4-character code of codec used to compress the frames. For example,CV_FOURCC(‘P’,‘I’,‘M’,‘1’)is a MPEG-1 codec, CV_FOURCC('M,‘J’,‘P’,‘G’) of codes can be obtained at Video Codecs by FOURCC page.
· fps - Framerate of the created video stream.
· frameSize - Size of the video frames.
·isColor - If it is not zero,the encoder will expect and encode color frames,otherwise it will work with grayscale frames(the flag is current)

  1. 写入帧方法

fourcc = cv2.VideoCapture('X','V','I', 'D')
out= cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))
out.write (frame)

  1. 注意事项:

写入视频前需安装对应的编解码器
生成视频是否支持彩色应与构造函数设置一致
生成视频尺寸需与读取视频尺寸一致

视频保存

import cv2
cap = cv2.VideoCapture('datas/vedioplay.mp4')
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)

#写入帧方法
fourcc = cv2.VideoWriter_fourcc(*'MJPG')  # opencv 3.0 #cv2.VideoWriter_fourcc('X','V','I','D')

#创建一个视频写入对象 VideoWriter
out = cv2.VideoWriter('datas/output20220617-1.mp4', fourcc, 20.0, (int(width), int(height)))
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    out.write(frame)

# Release everything if job is finished
cap.release()
cv2.destroyAllWindows()
23.1.3 简单实例应用

视频分解: 读取视频并分解为一张一张的图片保存

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977464.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号