一.Windows執行範例程式
1.範例程式
import cv2 import sys cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) video_capture = cv2.VideoCapture(0) while True: # 逐一以影格取像 ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) # 在辨識的臉形外圍畫一個矩形 for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # 呈現影像 cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # 停止執行 video_capture.release() cv2.destroyAllWindows()
2.執行結果
二.網路上的相關範例
import cv2 from webcam_gui import webcam_gui def imgproc(frame): # convert color to gray scale and show it gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('gray', gray) blur = cv2.blur(gray, (5,5)) edge = cv2.Canny(blur, 30, 100) edge = cv2.blur(edge, (2,2)) cv2.imshow('blured edge', edge) # convert image to black and white and show it thresh1, thresh = cv2.threshold(edge, 60, 255, cv2.THRESH_BINARY) cv2.imshow('thresh', thresh) # find contours! _,contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # draw all the contours cpframe = frame.copy() cv2.drawContours(cpframe, contours, -1, (0,255,0), 3) cv2.imshow('cpframe', cpframe) # ================== TODO =================== # Modify these code to suit your need contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100] contours = [cv2.approxPolyDP(ctr, 5 , True) for ctr in contours] contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)] # ============================================ # draw on the frame cv2.drawContours(frame, contours, -1, (0,255,0), 3) return frame if __name__ == "__main__": webcam_gui(imgproc, video_src=0)
1.執行結果
三.執行範例後心得
Comments
comments powered by Disqus