from PIL import Image import numpy as np # 读取原始图像 path = "output.bmp" original_image = Image.open(path) original_width, original_height = original_image.size # 定义裁剪后的新高度 new_height = original_height - 400 # 上下各裁剪200像素 # 裁剪图像,上下各裁剪200像素 # 左上角坐标为(0, 200),右下角坐标为(width, height-200) cropped_image = original_image.crop( (0, 200, original_width, original_height-200)) cropped_image.show() # 创建目标图像(1280x1024像素,灰度模式) target_width, target_height = 1280, 1024 target_image = Image.new("L", (target_width, target_height), color=0) # 计算图像放置位置 x_offset = (target_width - original_width) // 2 y_offset = (target_height - new_height) // 2 # 将原始图像放置在目标图像中央 target_image.paste(cropped_image, (x_offset, y_offset)) # 将目标图像转换为NumPy数组 target_array = np.array(target_image) # # 在周围填充随机噪声 # noise_level = 256 # 随机噪声的灰度级别 # noise = np.random.randint( # 0, noise_level, (target_height, target_width)).astype(np.uint8) # target_array = np.where(target_array == 0, noise, target_array) # # 创建包含噪声的新图像 # noisy_image = Image.fromarray(target_array.astype(np.uint8)) # # 保存为位图(BMP)图像 # noisy_image.save("black_"+path) # 创建黑色填充 black_color = 0 # 黑色像素值为0 target_array[:y_offset, :] = black_color # 上方填充 target_array[y_offset + original_height:, :] = black_color # 下方填充 target_array[:, :x_offset] = black_color # 左侧填充 target_array[:, x_offset + original_width:] = black_color # 右侧填充 # 创建包含黑色填充的新图像 padded_image = Image.fromarray(target_array) # 保存为位图(BMP)图像 padded_image.save("black_"+path)