如何在 OpenCV 中使用 Python 檢測影像中的貓臉?
Haar 級聯分類器是一種有效的物體檢測方法。它是一種基於機器學習的方法。為了訓練用於貓臉檢測的 Haar 級聯分類器,演算法最初需要大量的正樣本影像(包含貓臉的影像)和負樣本影像(不包含貓臉的影像)。分類器根據這些正樣本和負樣本影像進行訓練。然後用於檢測其他影像中的貓臉。
我們可以使用已經訓練好的 Haar 級聯進行微笑檢測。對於輸入影像中的微笑檢測,我們需要兩個 Haar 級聯,一個用於人臉檢測,另一個用於微笑檢測。我們將使用 **haarcascade_frontalcatface.xml** 來檢測影像中的貓臉。
如何下載 Haar 級聯?
您可以在以下 GitHub 網站地址找到不同的 Haar 級聯:
https://github.com/opencv/opencv/tree/master/data/haarcascades要下載用於貓臉檢測的 Haar 級聯,請點選 **haarcascade_frontalcatface.xml** 檔案。以原始格式開啟它,右鍵單擊並儲存。
步驟
要檢測影像中的貓臉並在其周圍繪製邊界框,您可以按照以下步驟操作:
匯入所需的庫。在以下所有示例中,所需的 Python 庫是 **OpenCV**。確保您已安裝它。
使用 **cv2.imread()** 讀取輸入影像。指定完整的影像路徑。將輸入影像轉換為灰度影像。
初始化一個用於貓臉檢測的 Haar 級聯分類器物件 **cat_cascade = cv2.CascadeClassifier()**。傳遞 Haar 級聯 xml 檔案的完整路徑。您可以使用 Haar 級聯檔案 **haarcascade_frontalcatface.xml** 來檢測影像中的貓臉。
使用 **cat_cascade.detectMultiScale()** 檢測輸入影像中的貓臉。它以 **(x,y,w,h)** 格式返回檢測到的貓臉的座標。
使用 **cv2.rectangle()** 在原始影像中檢測到的貓臉周圍繪製邊界矩形。
顯示帶有貓臉周圍繪製的邊界矩形的影像。
讓我們看一些在影像中檢測貓臉的示例。
示例
在本示例中,我們使用 Haar 級聯檢測輸入影像中的貓臉。
# import required libraries import cv2 # read the input image img = cv2.imread('cat.jpg') # convert the input image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # read the haarcascade to detect cat faces cat_cascade = cv2.CascadeClassifier('haarcascades\haarcascade_frontalcatface.xml') # Detects cat faces in the input image faces = cat_cascade.detectMultiScale(gray, 1.1, 3) print('Number of detected cat faces:', len(faces)) # if atleast one cat face id detected if len(faces) > 0: print("Cat face detected") for (x,y,w,h) in faces: # To draw a rectangle in a face cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2) cv2.putText(img, 'cat face', (x, y-3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1) else: print("No cat face detected") # Display an image in a window cv2.imshow('Cat Image',img) cv2.waitKey(0) cv2.destroyAllWindows()
我們將此影像用作此程式的 **輸入檔案**:
輸出
執行程式時,將生成以下輸出:
Number of detected cat faces: 1 Cat face detected
並且我們將獲得以下 **輸出** 視窗:
示例
在本示例中,我們使用 Haar 級聯檢測輸入影像中的貓臉。
# import required libraries import cv2 # read the input image img = cv2.imread('two-cats.jpg') # convert the input image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # read the haarcascade to detect cat faces cat_cascade = cv2.CascadeClassifier('haarcascades\haarcascade_frontalcatface.xml') # Detects cat faces in the input image faces = cat_cascade.detectMultiScale(gray, 1.1, 3) print('Number of detected cat faces:', len(faces)) # if atleast one cat face id detected if len(faces) > 0: for (x,y,w,h) in faces: print("Cat face detected") # To draw a rectangle in a face cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2) cv2.putText(img, 'cat face', (x, y-3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1) else: print("No cat face detected") # Display an image in a window cv2.imshow('Cat Image',img) cv2.waitKey(0) cv2.destroyAllWindows()
我們將此影像用作此程式的 **輸入檔案**:
執行後,將生成以下 **輸出**:
Number of detected cat faces: 2 Cat face detected Cat face detected
並且我們將獲得以下 **輸出** 視窗: