Im working on to transform images using X-skew using the following code
from PIL import Image
def x_skew_image(input_path, output_path, skew_factor):
# Open the input image
input_image = Image.open(input_path)
# Get the image dimensions
width, height = input_image.size
# Calculate the new width after skewing
new_width = int(width + abs(skew_factor) * height)
# Create a new image with the calculated width and the same height
output_image = Image.new("RGB", (new_width, height))
# Apply the skew transformation
for y in range(height):
x_offset = int(skew_factor * y)
for x in range(width):
if 0 <= x + x_offset < new_width:
output_image.putpixel((x + x_offset, y), input_image.getpixel((x, y)))
# Save the skewed image
output_image.save(output_path)
# Replace these paths and skew_factor as needed
input_path = r'input_path' # Replace with the path to your input image
output_path = r'output_path' # Replace with the desired output path
skew_factor = -0.4 # Adjust the skew factor as needed
x_skew_image(input_path, output_path, skew_factor)
However, Im facing issue when trying to with negative X-skewing (change skew_factor to negative value) and it seems that the image get cropped. How can i modify the code to solve the issue?
Your code works if you change it to this:
With
skew_factor=0.4:With
skew_factor=-0.4:However, I would really advise AGAINST using
forloops for image processing in Python - they are slow and error-prone. There is a noticeable delay when running your code versus using the built-in affine transform method which is instantaneous and simpler:Referring to your secondary question about filling the surrounding black area, you can try this for a solid greenish colour:
If you want to fill the undefined parts of your sheared image with a blurred version of your original image, you can do that like this - your tastes on blur radius and so on may vary but you should get the idea: