Ok, so the main problem is that you're trying to stretch the image using matrix multiplication between the original matrix and its inverse, which is not the correct approach for stretching an image. Simpler transformations like scaling rotating can be done with simple matrix multiplication, but when you're trying to stretch an image to fit a rectangle, it's not a simple matrix multiplication operation that's needed. This discussion on StackExchange might help you out with your approach.
An alternative to this would be using a simple interpolation-based approach. You can do this by creating a new blank image with the desired dimensions and then filling in the pixels using the original image.
Here is a modified version of your code to help you do this:
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")