我有这样的数据:x / y的面部中心,面部的高度和宽度,原始图像的高度和宽度。用户上传的图片的人脸可能在完全不同的地方,并且图片的长宽比可能有所不同。我使用openCV确定是否有人脸:
def crop_face(img, margin_x = 550, margin_y = 400):
image = cv2.imread(img)
height, width = image.shape[:2]
#print('width - {0}, height - {1}'.format(width, height))
face_cascade = cv2.CascadeClassifier(FACE_DETECTOR_PATH)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.29, 5)
print ("Found {0} faces!".format(len(faces)))
if len(faces) == 1:
for (x,y,w,h) in faces:
r = max(w, h) / 2
centerx = x + w / 2
centery = y + h / 2
nx = int(centerx - r)
ny = int(centery - r)
nr = int(r * 2)
print ('x - {0}, y - {1}, w - {2}, h - {3}'.format(x,y,w,h))
print ('r - {0}, centerX - {1}, centerY - {2}, nx - {3}, ny - {4},nr - {5}'.format(r,centerx,centery,nx,ny, nr))
margin_dict = get_normal_margin(margin_x, margin_y ,centerx, centery, height,width)
margin_dict['x_max'] -= int(w/2);
margin_dict['x_min'] -= int(w/2);
margin_dict['y_max'] -= int(h/2);
margin_dict['y_min'] -= int(h/2);
roi_color = image[y-margin_dict['y_min']:y + h+margin_dict['y_max'], x-margin_dict['x_min']:x + w +margin_dict['x_max']]#y max, y min, x max, x min
#roi_color = image[y:y+h, x:x+w]
return roi_color
因此尝试获取x和y的最大允许缩进量:
def get_normal_margin(margin_x, margin_y, center_x, center_y, height, width):
margin_to_return = {'y_max': margin_y, 'y_min': margin_y, 'x_max': margin_x, 'x_min': margin_x}
for x in range(int(center_x), width - int(center_x)):
if(x < margin_x and x > 0):
margin_to_return['x_max'] = x
for x in reversed(range(int(center_x), width - int(center_x))):
if(x < margin_x and x > 0):
margin_to_return['x_min'] = x
for x in range(int(center_y), height - int(center_y)):
if(x < margin_y and x > 0):
margin_to_return['y_max'] = x
for x in reversed(range(int(center_y), height - int(center_y))):
if(x < margin_y and x > 0):
margin_to_return['y_min'] = x
return margin_to_return
但不起作用。有些图像会切断标称值,有些则完全不正常。 以下是示例: I give the entrance getting output
here is an example of what is needed
我在正确的轨道上吗?