python
import os
import cv2
import json
def crop_face_with_bbox(image_path, bbox_path, save_path):
"""
使用head_bbox对图像进行裁剪并保存,支持自定义向上、向左右扩展区域。
Args:
image_path (str): 输入图像路径。
bbox_path (str): 包含head_bbox的JSON文件路径。
save_path (str): 保存裁剪后图像的路径。
Returns:
None
"""
try:
# 1. 读取图像
image = cv2.imread(image_path, cv2.IMREAD_COLOR)
if image is None:
print(f"无法读取图像: {image_path}")
return
# 2. 读取bounding box文件
with open(bbox_path, 'r') as f:
bbox_data = json.load(f)
# 假设 bbox 是以 "bbox": [w1, h1, w2, h2] 的格式存储的
if not bbox_data['data']:
print(f"空的bbox数据: {bbox_path}")
return
head_bbox = bbox_data['data'][0]['bbox'] # 使用第一个bbox
w1, h1, w2, h2 = head_bbox
w1, h1, w2, h2 = int(w1), int(h1), int(w2), int(h2)
# 获取图像的高和宽
h, w = image.shape[:2]
# --- 裁剪区域扩展逻辑 ---
# 向上扩展两倍高度
box_height = h2 - h1
h1 = max(0, h1 - 2 * box_height) # 向上扩展两倍高度
# 向下不扩展(保留原边界值 h2)
# 向左右扩展三倍宽度
box_width = w2 - w1
w1 = max(0, w1 - 3 * box_width) # 向左扩展三倍宽度
w2 = min(w, w2 + 3 * box_width) # 向右扩展三倍宽度
# 裁剪图像
cropped_face = image[h1:h2, w1:w2, :]
# 保存裁剪后的图像
if not os.path.exists(os.path.dirname(save_path)):
os.makedirs(os.path.dirname(save_path))
cv2.imwrite(save_path, cropped_face)
print(f"裁剪后的图像已保存到: {save_path}")
except Exception as e:
print(f"处理失败 - 图像: {image_path}, bbox: {bbox_path}, 错误: {e}")
def batch_process_images(txt_path, save_folder):
"""
根据给定的 txt 文件,读取图像路径并批量处理裁剪。
读取 txt 文件,生成图像路径与根据规则构造 bbox 路径。
Args:
txt_path (str): 包含图像路径的 txt 文件路径。
save_folder (str): 裁剪后图像的保存文件夹路径。
Returns:
None
"""
try:
# 读取 txt 文件内容
with open(txt_path, 'r') as f:
lines = f.readlines()
for line in lines:
# 获取图像路径,仅处理以 .jpg 结尾的文件
items = line.strip().split()
if len(items) < 1:
continue
image_path = items[0]
if not image_path.endswith('.jpg'): # 过滤非 .jpg 文件
continue
# 构造 bbox.json 的路径,假设路径规则为 *_1_bbox.json
base_name = os.path.basename(image_path) # 如:6587c2cb0000000007009360_7.jpg
bbox_name = base_name.replace('.jpg', '_1_bbox.json')
bbox_path = os.path.join(
"/home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/bbox", bbox_name
)
if not os.path.exists(bbox_path):
print(f"未找到对应的 bbox 文件: {bbox_path}")
continue
# 生成保存路径
save_path = os.path.join(
save_folder,
os.path.basename(image_path) # 保存时使用原来的图像文件名
)
# 调用裁剪函数
crop_face_with_bbox(image_path, bbox_path, save_path)
except Exception as e:
print(f"批量处理失败: {e}")
if __name__ == "__main__":
# 输入 txt 文件路径
txt_path = "image_and_mask_paths.txt" # 替换为你的 txt 文件路径
# 图像裁剪后保存的路径
save_folder = "/home/notebook/data/group/hzp/oppseg_v7/cropped_images" # 替换为保存文件夹路径
# 批量裁剪图像
batch_process_images(txt_path, save_folder)