您好,登錄后才能下訂單哦!
Python 小貓檢測,通過調用opencv自帶的貓臉檢測的分類器進行檢測。
分類器有兩個:haarcascade_frontalcatface.xml和
haarcascade_frontalcatface_extended.xml。可以在opencv的安裝目錄下找到
D:\Program Files\OPENCV320\opencv\sources\data\haarcascades
小貓檢測代碼為:
1. 直接讀取圖片調用
import cv2 image = cv2.imread("cat_04.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # load the cat detector Haar cascade, then detect cat faces # in the input image detector = cv2.CascadeClassifier("haarcascade_frontalcatface.xml") #haarcascade_frontalcatface_extended.xml rects = detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(100, 100)) # loop over the cat faces and draw a rectangle surrounding each print (enumerate(rects)) for (i, (x, y, w, h)) in enumerate(rects): cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(image, "Cat #{}".format(i + 1), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2) print (i, x,y,w,h) # show the detected cat faces cv2.imshow("Cat Faces", image) cv2.waitKey(1)
檢測效果:
2. 通過命令控制符調用
也可以通過調用argparse庫,進行整體調用
新建cat_detect.py文件
# import the necessary packages import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the input image") ap.add_argument("-c", "--cascade", default="haarcascade_frontalcatface_extended.xml", help="path to cat detector haar cascade") args = vars(ap.parse_args()) #"haarcascade_frontalcatface_extended.xml", # load the input image and convert it to grayscale #image = cv2.imread(args["image"]) image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # load the cat detector Haar cascade, then detect cat faces # in the input image detector = cv2.CascadeClassifier(args["cascade"]) rects = detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(120, 120)) # cat good # loop over the cat faces and draw a rectangle surrounding each print (enumerate(rects)) for (i, (x, y, w, h)) in enumerate(rects): cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(image, "cat #{}".format(i + 1), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2) # show the detected cat faces cv2.imshow("Cat Faces", image) cv2.waitKey(0)
通過“命令控制符”調用
cmd cd E:\WORK\py\detectCat E:\WORK\py\detectCat>python cat_detector.py --image cat_07.png
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。