从原图中同时裁剪多个人脸图像,保持位置不变,组合成新的灰度图

本文介绍了一种从原图中裁剪并扩大人脸图像的方法,通过Python和OpenCV实现,保持了人脸在图片中的相对位置不变。文章详细展示了如何构造矩形框定位人脸,并在灰度图上进行裁剪和绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/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()




效果如下原图,和裁剪后的组合图

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值