我正在尝试使用 python 检测照片中的人脸
# Import the excel file available
import os
import numpy as np, pandas as pd
import warnings
from PIL import Image
import matplotlib.pyplot as plt
import cv2
warnings.filterwarnings('ignore')
假设我有照片目录并且它存储在 pic_loc
# Load in color image for face detection
image = cv2.imread(pic_loc)
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Make a copy of the original image to draw face detections on
image_copy = np.copy(image)
# Convert the image to gray
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Detect faces in the image using pre-trained face dectector
faces = face_cascade.detectMultiScale(gray_image, 1.25, 6)
我在最后一点收到一个错误,它必须是一些错误
答案 0 :(得分:0)
您需要创建一个 cv2.CascadeClassifier()
对象。
<CascadeClassifier object> = cv2.CascadeClassifier( filename )
这是一个小例子:
import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('xyzjpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
答案 1 :(得分:0)
我真的很想感谢@Divyansh Chaudhary,但提供的解决方案并没有完全解决我的问题。诀窍是重新定义
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
唯一解决它的是以下。
# Import the excel file available
import os
import numpy as np, pandas as pd
import warnings
from PIL import Image
import matplotlib.pyplot as plt
import cv2
warnings.filterwarnings('ignore')
然后使用您可以执行的图像目录
# Load in color image for face detection
image = cv2.imread(pic_loc)
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Make a copy of the original image to draw face detections on
image_copy = np.copy(image)
# Convert the image to gray
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
# Detect faces in the image using pre-trained face dectector
faces = face_cascade.detectMultiScale(gray_image, 1.25, 6)