#!/usr/bin/env python
# -*- coding:utf-8 -*-
#@Time : 19-12-23 下午5:37
#@Author: Bryan
#@File : my_test.py
'''
从原图中裁剪部分人脸图像,保持位置不变,
'''
import cv2
import numpy as np
ratio=2#扩大比例
#画矩形框
def draw_box(image, box, color, thickness=2):
b = np.array(box).astype(int)
cv2.rectangle(image, (b[0], b[1]), (b[2], b[3]), color, thickness, cv2.LINE_AA)
def main():
img_raw = cv2.imread('000021.jpg')
img_raw = cv2.resize(img_raw, (300, 300), interpolation=cv2.INTER_AREA)
rows, cols, ch = img_raw.shape
#人为构造的矩形框,这里是图中的人脸位置
boxes = [[85.77092912833217, 55.85900957788992, 117.31985106905064, 85.6277261857844],
[73.34354348995345, 119.14695333675756, 97.40218765369889, 142.22525684652368],
[213.04298121836652, 31.373129018566782, 247.46504065882095, 59.70314650369884]
]
canvas = np.full((300, 300, 3), 128, dtype=np.uint8)#构造一个300*300*3的灰度图
for box in boxes:
draw_box(img_raw, box, color=(255, 0, 0)) # 红色画框
box = np.array(box).astype(int)
center_x = (box[0] + box[2]) // 2
center_y = (box[1] + box[3]) // 2
box_w = np.maximum(box[2] - box[0], box[3] - box[1])
new_box_s = int(box_w * ratio) // 2
box = (np.maximum(center_x - new_box_s, 0), np.maximum(center_y - new_box_s, 0),
np.minimum(center_x + new_box_s, cols), np.minimum(center_y + new_box_s, rows)) # x1,y1,x2,y2,在原始人脸的基础上,稍微扩大一些
canvas[box[1]:box[3], box[0]:box[2], :] = img_raw[box[1]:box[3], box[0]:box[2], :] #裁剪人脸图,保持位置不变
cv2.imwrite('a.jpg', img_raw) # 存档
cv2.imwrite('b.jpg', canvas) # 存档
if __name__ == '__main__':
main()
效果如下原图,和裁剪后的组合图