numpy 在Python中编写stretch_image函数

xam8gpfp  于 2023-10-19  发布在  Python
关注(0)|答案(1)|浏览(93)

我必须用python写一个函数来获取一个PIL图像并将其拉伸成矩形形状
我试着运行这段代码:

def stretch_image(im3D):
    width, height = im3D.size
    data = np.array(im3D, dtype=np.uint8)
    matrix = data.reshape(height, width)

    if not np.linalg.det(matrix):
        raise ValueError("The matrix is not invertible")
    invertible_matrix = np.linalg.inv(matrix)
    stretch3Dimg = matrix * invertible_matrix
    return stretch3Dimg

我希望能得到一张

zpgglvta

zpgglvta1#

好的,主要问题是你试图使用原始矩阵和它的逆矩阵之间的矩阵乘法来拉伸图像,这不是拉伸图像的正确方法。像缩放旋转这样更简单的变换可以用简单的矩阵乘法来完成,但是当你试图拉伸图像以适应矩形时,就不需要简单的矩阵乘法操作了。这个discussion on StackExchange可能会帮助你的方法。
对此的替代方案将是使用简单的基于插值的方法。您可以通过创建具有所需尺寸的新空白图像,然后使用原始图像填充像素来完成此操作。
下面是代码的修改版本,可以帮助您做到这一点:

import numpy as np
from PIL import Image

def stretch_image(im):
    target_width = 400  # Set the desired width of the rectangle
    target_height = 300  # Set the desired height of the rectangle

    # Calculate the scaling factors
    width_ratio = target_width / im.width
    height_ratio = target_height / im.height

    # Create a new blank image with the target dimensions
    stretched_im = Image.new("RGB", (target_width, target_height))

    # Loop through the pixels of the new image and fill them with interpolated values
    for y in range(target_height):
        for x in range(target_width):
            source_x = int(x / width_ratio)
            source_y = int(y / height_ratio)
            stretched_im.putpixel((x, y), im.getpixel((source_x, source_y)))

    return stretched_im

# Load your original image using PIL
original_image = Image.open("original_image.png")

# Stretch the image
stretched_image = stretch_image(original_image)

# Display or save the stretched image as needed
stretched_image.show()
stretched_image.save("stretched_image.jpg")

相关问题