Python实现猫脸识别 | 喵主子福利
一篇文章带你了解Python实现猫脸识别
pip install opencv-python pillow
import cv2
from PIL import Image
# Load the cascades
catface_cascade = cv2.CascadeClassifier('catface_detector.xml')
humanface_cascade = cv2.CascadeClassifier('humanface_detector.xml')
newsize = (600, 600)
#First image retouches
imgr1 = Image.open("test1.jpg")
imgr1 = imgr.resize(newsize)
imgr1.save("resized1.jpg")
#Second image retouches
imgr2 = Image.open("test2.jpg")
imgr2 = imgr.resize(newsize)
imgr2.save("resized2.jpg")
imgr1 = imgr1.convert('L')
imgr1.save('ready1.jpg')
imgr2 = imgr2.convert('L')
imgr2.save("ready2.jpg")
# Read the input image
img1 = cv2.imread('ready1.jpg')
img2 = cv2.imread('ready2.jpg')
human_faces = humanface_cascade.detectMultiScale(img1,
scaleFactor=1.3, minNeighbors=5, minSize=(75, 75))
cat_faces = catface_cascade.detectMultiScale(img2, scaleFactor=1.3,
minNeighbors=5, minSize=(75, 75))
for (i, (x, y, w, h)) in enumerate(human_faces):
cv2.rectangle(img1, (x, y), (x+w, y+h), (220, 90, 230), 3)
cv2.putText(img1, "Human Face - #{}".format(i + 1), (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (220, 90, 230), 2)
for (i, (x, y, w, h)) in enumerate(cat_faces):
cv2.rectangle(img2, (x, y), (x+w, y+h), (0,255, 0), 3)
cv2.putText(img2, "Cat Faces - #{}".format(i + 1), (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2)
#Saving the images using imwrite method
cv2.imwrite("faces_detected1.png", img1)
cv2.imwrite("faces_detected2.png", img2)
· END ·
评论