如何使用Python裁剪带有黑白双色边框的图像
旋转图像黑白边框裁剪Python实现
前置依赖安装
首先安装轻量图像处理库Pillow,适合新手快速上手:pip install pillow numpy
实现逻辑
我们通过判断像素值的方式自动定位核心区域边界:
- 纯黑边框像素值为0,纯白边框像素值为255,核心区域像素值在1-254之间
- 分别从图片的上、下、左、右四个方向逐行/逐列扫描,找到第一个出现非边框像素的位置作为裁剪边界
- 按照边界裁剪后输出无多余边框的核心图像
可直接运行代码
from PIL import Image import numpy as np # 1. 读取待裁剪的旋转后图像,替换为你自己的图片路径 img = Image.open("你的旋转后图片路径.png") # 转为灰度图方便像素判断 gray_img = img.convert("L") # 转为numpy数组操作更高效 img_arr = np.array(gray_img) # 2. 计算上下裁剪边界 # 上边界:从顶部开始找第一个有非0/255像素的行 top = 0 while top < img_arr.shape[0] and np.all((img_arr[top] == 0) | (img_arr[top] == 255)): top += 1 # 下边界:从底部开始找第一个有非0/255像素的行 bottom = img_arr.shape[0] - 1 while bottom >= 0 and np.all((img_arr[bottom] == 0) | (img_arr[bottom] == 255)): bottom -= 1 # 3. 计算左右裁剪边界 # 左边界:从最左侧开始找第一个有非0/255像素的列 left = 0 while left < img_arr.shape[1] and np.all((img_arr[:, left] == 0) | (img_arr[:, left] == 255)): left += 1 # 右边界:从最右侧开始找第一个有非0/255像素的列 right = img_arr.shape[1] - 1 while right >= 0 and np.all((img_arr[:, right] == 0) | (img_arr[:, right] == 255)): right -= 1 # 4. 裁剪图像并保存 cropped_img = img.crop((left, top, right+1, bottom+1)) # 替换为你想要的输出路径 cropped_img.save("裁剪后核心图像.png") # 可选:直接显示裁剪结果 cropped_img.show()
注意事项
- 如果你的边框不是绝对纯黑/纯白,可以调整代码里的像素判断阈值,比如将
==0改为<10,==255改为>245即可适配有轻微噪点的边框 - 如果不需要安装numpy,也可以直接用Pillow的
getpixel()方法逐点遍历,只是处理大图片时速度稍慢
内容的提问来源于stack exchange,提问作者Teoh
相关产品推荐
相关产品推荐

