我正在尝试检测一张脸然后裁剪它以在脸部识别算法中使用它。这是我的代码。
import numpy as np
import cv2
import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('xD.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = 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]
print x
print y
print w
print h
img.crop((x,y,w,h))
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
当我打印(x,y,w,h)时,它会给出精确的坐标,但是当我裁剪它时,它会给我这个错误。
img.crop((X,Y,W,H))
AttributeError:'numpy.ndarray'对象没有属性'crop'
答案 0 :(得分:1)
import numpy as np
import cv2
from PIL import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('xD.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = 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]
cropped = img[y:y+h, x:x+w]
cv2.imwrite("thumbnail.png", cropped)
cv2.imshow("cropped", cropped)
cv2.waitKey(0)