OpenCV-python学习笔记(一)——工具使用

本文是OpenCV-Python学习的第一部分,涵盖了读取、保存、显示图像,视频基础操作,绘图函数,鼠标事件以及使用滑动条作为调色板。适合初学者,提供详细的操作指南。
摘要由CSDN通过智能技术生成

为了快速学习,按照中文教程中的顺序,走一遍python接口。英文能力较强者,可以从对应的英文教程自己翻译学习。
另: 自认为挺好的一个教程博客。共有四个系列,比较全面详细,适合初学者。

学习环境

	python3.5、opencv、numpy、matplotlib

一、读取、保存、显示图像

  1. cv2.imread(文件名,标记)读入图像,标记可以是以下方法。分别对应1,0;
    *cv2.MREAD_COLOR():读入彩色图像;
    *cv2.IMREAD_GRAYSCALE():以灰度模式读入图像;
  2. cv2.imshow():显示图像;
    *cv2.waitKey():等待键盘输入,为毫秒级;
    *cv2.destroyAllWindows():可以轻易删除任何我们建立的窗口,括号内输入想删除的窗口名;
  3. cv2.imwrite(文件名,img):保存图像;
  4. 练习加载一个灰度图,显示图片,按下‘s’键保存后退出,或者按下ESC键退出不保存;
import numpy as np
import cv2

img = cv2.imread('45.jpg',0)
cv2.imshow('image',img)
k = cv2.waitKey(0)
if k==27:
		cv2.destroyAllWindows()  #wait for ESC key to exit
elif k == ord('s'):
		cv2.imwrite('46.png',img)  #wait for 's' key to save and exit
        cv2.destoryAllWindows()

如果用的是64位系统,需将key=cv2.waitKey(0)改为k=cv2.waitKey(0)&0xFF @!!

  1. Matplotlib绘图库的使用,先简单介绍显示图像,更多信息去菜鸟教程
import numpy as np
import cv2
from matplotlib import pyplot as plt
img =cv2.imread('45.jpg',0)
plt.imshow(img,cmap='gray',interpolation = 'bicubic')
plt.xticks([]),plt.yticks([])  #to hide tick values on X and Y axis
plt.show()

注意:如果图像的像素过大,可能会plt.imshow()函数报错。

二 、视频基础操作

1.用摄像头捕获视频

  • cv2.VideoCapture() :0为默认计算机默认摄像头,1可以更换来源(如USB外接摄像头等),也可以是网络视频;
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
	#capture frame-by-frame
    ret , frame = cap.read()
    
    #our operation on the frame come here
    gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
    
    #display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) &0xFF ==ord('q'):  #按q键退出
    	break
#when everything done , release the capture
cap.release()
cv2.destroyAllWindows()
  • cap.isOpened();检查是否成功初始化了,返回值是True,就没有问题,否则就要使用cap.open()。

  • cap.get(propId);获取视频的一些参数信息。
    propId 可以是 0 到 18 之间的任何整数。每一个数代表视频的一个属性:

      • CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.  
      (0-视频文件的当前位置(毫秒))
      • CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next. 
      (1-下一步要解码/捕获的帧的基于0的索引)
      • CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film. 
      (2-视频文件的相对位置:0-胶片开始,1-胶片结束)
      • CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream. 
      (3-视频流中帧的宽度)
      • CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream. 
      (4-视频流中帧的高度)
      • CV_CAP_PROP_FPS Frame rate. 
      (5-帧率)
      • CV_CAP_PROP_FOURCC 4-character code of codec. 
      (6-编解码器的4字符代码)
      • CV_CAP_PROP_FRAME_COUNT Number of frames in the video file. 
      (7-视频文件中的帧数。)
      • CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() . 
      (8-返回mat对象的格式)
      • CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode. 
      (9-后端特定值,指示当前捕获模式)
      • CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras). 
      (10-图像的亮度--仅适用于相机)
      • CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras). 
      (11-对比度--仅用于相机)
      • CV_CAP_PROP_SATURATION Saturation of the image (only for cameras). 
      (12-饱和度--仅用于相机)
      • CV_CAP_PROP_HUE Hue of the image (only for cameras). 
      (13-色调--仅用于相机)
      • CV_CAP_PROP_GAIN Gain of the image (only for cameras). 
      (14-增益--仅用于相机)
      • CV_CAP_PROP_EXPOSURE Exposure (only for cameras). 
      (15-曝光--仅用于相机)
      • CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
      (16-布尔标志,指示是否应将图像转换为RGB。) 
      • CV_CAP_PROP_WHITE_BALANCE Currently unsupported 
      (17-当前不受支持)
      • CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently) 
      (18-立体摄像机的校正标志(注:目前仅受DC1394 v 2.x后端支持))
      对应的,使用 cap.set(propId,value) 来修改视频属性,value 就是你想要设置成的新值。
    
  • cap.set(propId,value);修改参数信息。

2.从文件中播放视频

把设备索引号改成文件名即可。在播放每一帧时,使用cv2.waitKey()适当持续时间,一般可以设置25ms。

import numpy as np
import cv2
cap=cv2.VideoCapture('filename.avi')#文件名及格式
while(True):
	#capture frame-by-frame
    ret , frame = cap.read()
    
    #our operation on the frame come here
    gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)# 转化为灰度像素
    
    #display the resulting frame
    cv2.imshow('frame',gray)#显示灰度视频
    if cv2.waitKey(1) &0xFF ==ord('q'):  #按q键退出
    	break
#when everything done , release the capture
cap.release()
cv2.destroyAllWindows()

3 .保存视频

创建一个VideoWrite的对象,确定输出文件名,指定FourCC编码,播放频率和帧的大小,最后是isColor标签True为彩色。
FourCC是一个4字节码,用来确定视频的编码格式。

  1. In Fedora : DIVX , XVID , MJPG , X264 , WMV1 , WMV2
    XVID是最好的,MJPG是高尺寸视频,X264得到小尺寸视频
  2. In Windows : DIVX
  3. In OSX :不知道用什么好

设置FourCC格式时,原文里采用了cv2.VideoWriter_fourcc()这个函数,若运行程序的时候显示这个函数不存在,可以改用了cv2.cv.CV_FOURCC这个函数。

  • cv2.flip(frame,1);图像翻转,1ÿ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值