我正在努力使用以下代码使用 X 倾斜来转换图像
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)
但是,当尝试使用负 X 倾斜(将 skew_factor 更改为负值)时,我遇到了问题,并且图像似乎被裁剪了。我该如何修改代码来解决这个问题?
如果您将其更改为这样,您的代码就可以工作:
#!/usr/bin/env python3
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)
if skew_factor < 0:
x_offset = int(-skew_factor * (height - y))
for x in range(width):
new_x = x + x_offset
if (new_x >= 0 ) and (new_x < new_width):
output_image.putpixel((new_x, 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 = 'CrazyCat.jpg'
output_path = 'result.jpg'
skew_factor = -0.4 # Adjust the skew factor as needed
x_skew_image(input_path, output_path, skew_factor)
与
skew_factor=0.4
:
与
skew_factor=-0.4
:
但是,我真的建议 AGAINST 使用
for
循环在 Python 中进行图像处理 - 它们很慢并且容易出错。与使用即时且更简单的内置仿射变换方法相比,运行代码时存在明显的延迟:
#!/usr/bin/env python3
from PIL import Image
input_path = 'CrazyCat.jpg'
output_path = 'result.jpg'
im = Image.open(input_path)
w , h = im.size
shear_factor = 0.4
new_width = int(w + abs(shear_factor)*h)
if shear_factor > 0:
res = im.transform((new_width,h), Image.AFFINE, (1, shear_factor, -shear_factor*h, 0, 1, 0))
else:
res = im.transform((new_width,h), Image.AFFINE, (1, shear_factor, 0, 0, 1, 0))
res.save('result.jpg')