我试图编写一个python程序,它会裁剪图像以删除多余的空格。为此,我遍历整个图像以查找最左边,最右边,最上面和最下面的像素,以确定裁剪的必要边界。我的代码遗漏了左侧,右侧和底部边界上的一些像素。第一幅图像是源图像,另一幅是合成图像。Python:为什么我的代码不能正确裁剪选定的图像?
这里是我的代码:
import PIL
from PIL import Image
import os
bw = Image.open('abw.png')
width, height = bw.size
top, bottom, left,right = 100,-10,100,-10 #The given image 90x90
for x in range(height):
for y in range(width):
if(bw.getpixel((x,y))<255):
#if black pixel is found
if(y<left):
left = y
if(y>right):
right = y
if(x<top):
top = x
if(x>bottom):
bottom = x
bw.crop((left,top,right,bottom)).save('abw1.png')
有人能在我的代码找出问题?
你想用for循环来实现什么?你能否详细说明一下吗? –
For循环遍历图像并查找有用的边界值。正如你在这张图片中看到的那样,它周围没有多余的空白。 – user3566211