Python opencv cutout is centered to save the white background image

import os
import cv2
import numpy as np

def resize_and_center_image(image_path, output_path, size=450, canvas_size=500):
    img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)

    mask = np.zeros(img.shape, dtype=np.uint8)

    non_transparent_pixels = np.where(img[:, :, 3] != 0)

    # 使用非透明的像素更新掩码
    mask[non_transparent_pixels] = img[non_transparent_pixels]

    # 找到掩码的边界
    x, y, w, h = cv2.boundingRect(img[:, :, 3])

    # 使用边界裁剪掩码
    original_image = mask[y:y + h, x:x + w]

    # 显示前景
    # cv2.imshow('Foreground', foreground)

    # 获取图像的原始大小
    h, w = original_image.shape[:2]

    # 计算新的图像大小,保持长宽比
    if h > w:
        new_h, new_w = size, int(size * w / h)
    else:
        new_h, new_w = int(size * h / w), size

    # 缩放图像
    resized_image = cv2.resize(original_image, (new_w, new_h), interpolation=cv2.INTER_AREA)

    # 创建一个空白的白色画布
    canvas = np.ones((canvas_size, canvas_size, 3), dtype=np.uint8) * 255

    # 计算新图像在画布上的位置
    x = (canvas_size - new_w) // 2
    y = (canvas_size - new_h) // 2

    # 如果图像有 alpha 通道,将 alpha 通道转换为掩码
    if resized_image.shape[2] == 4:
        alpha = cv2.cvtColor(resized_image, cv2.COLOR_BGRA2GRAY)
        _, mask = cv2.threshold(alpha, 1, 255, cv2.THRESH_BINARY)
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
        mask = mask / 255.0

        # 使用掩码将图像和白色背景合并
        resized_image = resized_image[:, :, :3] * mask + (1.0 - mask) * 255

    # 将新图像放置在画布上
    canvas[y:y+new_h, x:x+new_w] = resized_image

    # 保存图像
    cv2.imwrite(output_path, canvas)

# 指定输入和输出目录
input_dir = 'a'
output_dir = 'b'

# 如果输出目录不存在,创建它
os.makedirs(output_dir,exist_ok=True)

# 列出输入目录下的所有文件
for filename in os.listdir(input_dir):
    # 只处理.png文件
    if filename.endswith('.png'):
        input_path = os.path.join(input_dir, filename)
        # 保存为.jpg文件
        output_filename = filename.rsplit('.', 1)[0] + '.jpg'
        output_path = os.path.join(output_dir, output_filename)
        resize_and_center_image(input_path, output_path)

Guess you like

Origin blog.csdn.net/jacke121/article/details/132675336