OpenCV图片和视频的处理函数总结

第一部分:Getting Started with Images

1、Read an image

函数:cv2.imread()

附带参数说明:

  • IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
  • IMREAD_GRAYSCALE : Loads image in grayscale mode
  • IMREAD_UNCHANGED : Loads image as such including alpha channel

注意:Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.

2、Display an image

函数: cv2.imshow()

3、Write an image

函数: cv2.imwrite()

4、A keyboard binding function

函数: cv2.waitKey()

5、destroys all the windows we created

函数:cv2.destroyAllWindows()

6、Sum it up

import cv2                       # 引入Opencv库
img = cv2.imread('obama.jpg',1)   # 指定图片的路径,这样写表示图片与本Python文件同级
cv2.imshow('image',img)           # 展示图片
# k = cv2.waitKey(0)
k = cv2.waitKey(0) & 0xFF         # 等待外部键盘输入
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('D:\messigray.png',img)     #将图片保存到D盘路径下
cv2.destroyAllWindows()                 #销毁图片

7、Using Matplotlib to show imags

Matplotlib is a plotting library for Python which gives you wide variety of plotting methods. You will see them in coming articles. Here, you will learn how to display image with Matplotlib. You can zoom images, save it etc using Matplotlib.

# -*- coding: utf-8 -*-
import cv2                              # 引入opencv库
from matplotlib import pyplot as plt   # 引入matplotlib库
img = cv2.imread('1.jpg',0)              # 载入一张图片,0参数表示灰度
plt.imshow(img,cmap = 'gray', interpolation = 'bicubic')     # 设置相关参数
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()                              # 用matplotlib展现图片

 

8、参考资料

资料1(opencv之Images使用):

http://docs.opencv.org/3.3.0/dc/d2e/tutorial_py_image_display.html

资料2(Matplotlib之imshow函数使用):

http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow

资料3(Matplotlib使用):

http://matplotlib.org/api/pyplot_api.html

 

第二部分:Getting Started with Videos

1、Capture Video from Camera

函数:cv2.VideoCapture()

函数:cap.read()

函数:cap.isOpened()

函数:cap.open()

# -*- coding: utf-8 -*-
import cv2                  # 引入opencv库
cap = cv2.VideoCapture(0)    # 创建一个VideoCapture对象,表示连接摄像头的索引,0表示第一个,以此类推
while(True):
# Capture frame-by-frame
ret, frame = cap.read()  # 一帧一帧地读取视频流,函数read()返回值为True或者false,可以判断frame是否正确读取
# 摄像头是否打开,可以通过cap.isOpened()进行判断,是,则返回True;否,则可以用cap.open()打开
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 设置获取视频的颜色
# 用户还可以设置框架的宽和高,cap.get(cv2.CAP_PROP_FRAME_WIDTH) and cap.get(cv2.CAP_PROP_FRAME_HEIGHT),默认值为640*480
# 如果设置成320*240. ret = cap.set(cv2.CAP_PROP_FRAME_WIDTH,320) and ret = cap.set(cv2.CAP_PROP_FRAME_HEIGHT,240).
# Display the resulting frame
cv2.imshow('frame',gray)  # 展示视频
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()                   # 释放VideoCapture对象
cv2.destroyAllWindows()

注意:

If you are getting error, make sure camera is working fine using any other camera application (like Cheese in Linux).

 

2、Playing Video from file

函数:cv2.VideoCapture()

函数:cap.read()

函数:cap.isOpened()

函数:cap.open()

# -*- coding: utf-8 -*-
import cv2
cap = cv2.VideoCapture('output.avi')    # 创建一个VideoCapture对象
while(cap.isOpened()):                 # 可以通过cap.isOpened()进行判断,摄像头是否打开,是,则返回True
ret, frame = cap.read()             # 一帧一帧地读取视频流
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)   # 设置颜色参数
cv2.imshow('frame',gray)                         # 视频展现
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()                           # 释放VideoCapture对象
cv2.destroyAllWindows()

注意:

Make sure proper versions of ffmpeg or gstreamer is installed. Sometimes, it is a headache to work with Video Capture mostly due to wrong installation of ffmpeg/gstreamer.

 

3、Saving a VIdeo

函数:cv2.imwrite().

函数:cv2.VideoWriter_fourcc(*'XVID')

函数:cv2.VideoWriter_fourcc('M','J','P','G')

函数:cv2.VideoWriter_fourcc(*'MJPG')

函数: FourCC code

FourCC 解析:FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org. It is platform dependent. Following codecs works fine for me.

  • In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video)
  • In Windows: DIVX (More to be tested and added)
  • In OSX: MJPG (.mp4), DIVX (.avi), X264 (.mkv).

FourCC code is passed as `cv2.VideoWriter_fourcc('M','J','P','G')or cv2.VideoWriter_fourcc(*'MJPG')` for MJPG.

# -*- coding: utf-8 -*-
import cv2
cap = cv2.VideoCapture(0)           # 创建一个VideoCapture对象
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')   # 定义FourCC code
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480),)   # 创建一个VideoWriter对象,定义输出视频名称,参数20表示每秒的帧数,以及框架的大小,最后面的参数表示颜色的标志,True表示有颜色,否则表示grayscale
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else
:
break
# Release everything if job is finished
cap.release()   # 释放VideoCapture对象
out.release()   # 释放VideoWriter对象
cv2.destroyAllWindows()

 

4、参考资料

资料1(opencv之Video使用):

http://docs.opencv.org/3.3.0/dd/d43/tutorial_py_video_display.html

资料2(FourCC):

https://en.wikipedia.org/wiki/FourCC

 

发表评论

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