python超搞笑的技能:調用opencv實現貓臉檢測功能

@本文來源於公衆號:csdn2299,喜歡可以關注公衆號 程序員學府

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

在這裏插入圖片描述
非常感謝你的閱讀
大學的時候選擇了自學python,工作了發現吃了計算機基礎不好的虧,學歷不行這是沒辦法的事,只能後天彌補,於是在編碼之外開啓了自己的逆襲之路,不斷的學習python核心知識,深入的研習計算機基礎知識,整理好了,我放在我們的微信公衆號《程序員學府》,如果你也不甘平庸,那就與我一起在編碼之外,不斷成長吧!

其實這裏不僅有技術,更有那些技術之外的東西,比如,如何做一個精緻的程序員,而不是“屌絲”,程序員本身就是高貴的一種存在啊,難道不是嗎?[點擊加入]想做你自己想成爲高尚人,加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章