You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Numpy将816×624图像转为640×640(居中裁剪+补黑边)

解决方案:将816×624图像转为640×640(居中裁剪+黑边填充)

原代码无法运行的核心原因是:原图像高度仅624,小于目标尺寸的640,直接按640高度范围切片会出现索引越界。正确的处理逻辑是分两步走:先对长边(宽度816)做居中裁剪,再对短边(裁剪后的高度624)做上下居中黑边填充。

方法一:使用PIL库实现

from PIL import Image

# 打开原图像
img = Image.open("your_image.jpg")
w1, h1 = img.size  # 816, 624

# 第一步:居中裁剪长边(宽度)到640
crop_left = (w1 - 640) // 2
crop_right = crop_left + 640
cropped_img = img.crop((crop_left, 0, crop_right, h1))  # 得到640×624的图像

# 第二步:创建640×640的黑底图像,居中粘贴裁剪后的图
target_size = (640, 640)
filled_img = Image.new("RGB", target_size, (0, 0, 0))
paste_top = (target_size[1] - cropped_img.height) // 2
filled_img.paste(cropped_img, (0, paste_top))

# 保存或显示结果
filled_img.save("result.jpg")
filled_img.show()

方法二:使用OpenCV库实现

import cv2
import numpy as np

# 读取原图像
img = cv2.imread("your_image.jpg")
h1, w1 = img.shape[:2]  # 624, 816

# 第一步:居中裁剪长边(宽度)到640
crop_x_start = (w1 - 640) // 2
crop_x_end = crop_x_start + 640
cropped_img = img[:, crop_x_start:crop_x_end]  # 得到624×640的图像(注意OpenCV的shape是高×宽)

# 第二步:创建640×640的黑底图像,居中放置裁剪后的图
target_h, target_w = 640, 640
filled_img = np.zeros((target_h, target_w, 3), dtype=np.uint8)
paste_y_start = (target_h - h1) // 2
filled_img[paste_y_start:paste_y_start+h1, :] = cropped_img

# 保存或显示结果
cv2.imwrite("result.jpg", filled_img)
cv2.imshow("Result", filled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

两种方法都能实现需求:先把原图像的长边从816裁剪到640(保留中心区域),再给上下补16像素的黑边((640-624)/2=16),最终得到640×640的图像。

内容的提问来源于stack exchange,提问作者sharkyenergy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:25:39