如何在Python中实现图像列偏移以校正斜线
列偏移实现图像斜线校正的Python方案
直接上可运行的代码,基于PIL和numpy实现你的需求:
from PIL import Image import numpy as np # 替换成你的图像路径 input_path = "input_image.png" output_path = "corrected_image.png" # 读取图像,支持RGB和灰度图 img = Image.open(input_path) img_np = np.array(img) h, w = img_np.shape[:2] channels = img_np.shape[2] if len(img_np.shape) == 3 else 1 # 计算目标图像尺寸:高度 = 原图高度 + 最大偏移量(原图列数),宽度和原图一致 max_offset = w # 第w列偏移w像素 target_h = h + max_offset # 创建黑色背景的目标数组 if channels == 1: target_np = np.zeros((target_h, w), dtype=np.uint8) else: target_np = np.zeros((target_h, w, channels), dtype=np.uint8) # 逐列偏移复制 for col_idx in range(w): # 第col_idx+1列(对应你的描述)偏移col_idx+1像素 offset = col_idx + 1 # 将原图当前列复制到目标图的对应列,从offset位置开始 if channels == 1: target_np[offset:offset+h, col_idx] = img_np[:, col_idx] else: target_np[offset:offset+h, col_idx, :] = img_np[:, col_idx, :] # 转换为图像并保存 result_img = Image.fromarray(target_np) result_img.save(output_path)
代码说明
- 支持RGB和灰度两种图像格式,自动适配通道数
- 目标图像高度是原图高度加上最大偏移量(原图的列数),确保所有偏移后的列都能完整放下
- 每一列的偏移量严格匹配你的要求:第1列(代码中
col_idx=0)偏移1像素,第2列偏移2像素,以此类推 - 如果需要向上偏移而非向下,只需把
offset替换为target_h - h - offset,调整起始位置即可
内容的提问来源于stack exchange,提问作者Annie
相关产品推荐
相关产品推荐

