Python去掉图片黑色边框
时间: 2023-11-19 11:49:07 浏览: 62
要去掉图片的黑色边框,可以使用以下代码:
```python
from PIL import Image
def remove_black_border(image_path):
image = Image.open(image_path)
width, height = image.size
pixels = image.load()
top = 0
bottom = height
left = 0
right = width
# 找到顶部边界
for i in range(height):
for j in range(width):
if pixels[j, i] != (0, 0, 0):
top = i
break
if top != 0:
break
# 找到底部边界
for i in range(height-1, -1, -1):
for j in range(width):
if pixels[j, i] != (0, 0, 0):
bottom = i+1
break
if bottom != height:
break
# 找到左边界
for i in range(width):
for j in range(top, bottom):
if pixels[i, j] != (0, 0, 0):
left = i
break
if left != 0:
break
# 找到右边界
for i in range(width-1, -1, -1):
for j in range(top, bottom):
if pixels[i, j] != (0, 0, 0):
right = i+1
break
if right != width:
break
new_image = image.crop((left, top, right, bottom))
new_image.save('result.png')
```
使用该函数 `remove_black_border` 可以去掉图片的黑色边框。你需要将图片的路径作为参数传递给该函数。函数将裁剪掉边框后的图片保存为 "result.png"。