red0orange

red0orange

對圖像進行pad+resize

代碼#

import cv2
import numpy as np


def pad_resize_image(image, width, height):
    # 獲取原始圖像的尺寸
    original_height, original_width = image.shape[:2]

    # 計算縮放比例
    scale = min(width / original_width, height / original_height)

    # 計算縮放後的新尺寸
    new_width = int(original_width * scale)
    new_height = int(original_height * scale)

    # 縮放圖像
    resized_image = cv2.resize(image, (new_width, new_height))

    # 創建新的畫布,並將縮放後的圖像放置在其中心
    if len(resized_image.shape) == 3:
        padded_image = np.zeros((height, width, resized_image.shape[2]), dtype=np.uint8)
    else:
        padded_image = np.zeros((height, width), dtype=np.uint8)
    start_x = (width - new_width) // 2
    start_y = (height - new_height) // 2
    padded_image[start_y:start_y + new_height, start_x:start_x + new_width] = resized_image

    # 計算從目標坐標系到原始坐標系的變換矩陣
    scale_matrix = np.eye(3)
    scale_matrix[0, 0] = scale
    scale_matrix[1, 1] = scale
    translation_matrix = np.eye(3)
    translation_matrix[0, 2] = start_x
    translation_matrix[1, 2] = start_y
    transformation_matrix = translation_matrix.dot(scale_matrix)

    return padded_image, transformation_matrix


if __name__ == "__main__":
    image = cv2.imread("test.png")
    new_image, _ = pad_resize_image(image, 256, 256)
    cv2.imshow("image", new_image)
    cv2.waitKey(0)
    pass
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。