Python-OpenCV 处理视频(二): 视频处理

0x00. 使用 Canny 算法边缘识别

Canny 算法是一种多级边缘识别算法。

Canny边缘识别算法可以分为以下5个步骤:

  1. 应用高斯滤波来平滑图像,目的是去除噪声。

  2. 找寻图像的强度梯度(intensity gradients)。

  3. 应用非最大抑制(non-maximum suppression)技术来消除边误检(本来不是但检测出来是)。

  4. 应用双阈值的方法来决定可能的(潜在的)边界。

  5. 利用滞后技术来跟踪边界。

具体原理性质的东西可以参考这里

读取本地视频处理代码示例:

12345678910111213141516171819202122 import cv2.cv as cv capture = cv.CaptureFromFile(\’img/myvideo.avi\’) nbFrames = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT))fps = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FPS)wait = int(1/fps * 1000/1) dst = cv.CreateImage((int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH)),                        int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))), 8, 1) for f in xrange( nbFrames ):     frame = cv.QueryFrame(capture)     cv.CvtColor(frame, dst, cv.CV_BGR2GRAY)    cv.Canny(dst, dst, 125, 350)    cv.Threshold(dst, dst, 128, 255, cv.CV_THRESH_BINARY_INV)     cv.ShowImage(\”The Video\”, frame)    cv.ShowImage(\”The Dst\”, dst)    cv.WaitKey(wait)

直接处理摄像头视频:

12345678910111213141516171819 import cv2.cv as cv capture = cv.CaptureFromCAM(0) dst = cv.CreateImage((int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH)),                        int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))), 8, 1) while True:    frame = cv.QueryFrame(capture)    cv.CvtColor(frame, dst, cv.CV_BGR2GRAY)    cv.Canny(dst, dst, 125, 350)     cv.Threshold(dst, dst, 128, 255, cv.CV_THRESH_BINARY_INV)    cv.ShowImage(\”The Video\”, frame)    cv.ShowImage(\”The Dst\”, dst)     c = cv.WaitKey(1)    if c == 27: #Esc on Windows        break

0x01. 人脸识别

使用OpenCV可以很简单的检测出视频中的人脸等:

1234567891011121314151617 import cv2.cv as cv capture=cv.CaptureFromCAM(0) hc = cv.Load(\”haarcascades/haarcascade_frontalface_alt.xml\”) while True:frame=cv.QueryFrame(capture)faces = cv.HaarDetectObjects(frame, hc, cv.CreateMemStorage(), 1.2,2, cv.CV_HAAR_DO_CANNY_PRUNING, (0,0) ) for ((x,y,w,h),stub) in faces:    cv.Rectangle(frame,(int(x),int(y)),(int(x)+w,int(y)+h),(0,255,0),2,0)     cv.ShowImage(\”Window\”,frame)    c=cv.WaitKey(1)    if c==27 or c == 1048603: #If Esc entered        break