0x00. 使用 Canny 演算法邊緣識別
Canny 演算法是一種多級邊緣識別演算法。
Canny邊緣識別演算法可以分為以下5個步驟:
-
應用高斯濾波來平滑影象,目的是去除噪聲。
-
找尋影象的強度梯度(intensity gradients)。
-
應用非最大抑制(non-maximum suppression)技術來消除邊誤檢(本來不是但檢測出來是)。
-
應用雙閾值的方法來決定可能的(潛在的)邊界。
-
利用滯後技術來跟蹤邊界。
具體原理性質的東西可以參考這裡
讀取本地視訊處理程式碼示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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) |
直接處理攝像頭視訊:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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可以很簡單的檢測出視訊中的人臉等:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 |