Python:为什么我的代码没有正确裁剪选定的图像?

Python: Why is my code not cropping a selected image properly?

我正在尝试编写一个 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')

有人能找出我代码中的问题吗?

您上传的图片是 JPG,而不是 PNG,因此其中可能存在一些解码伪像 该算法将非常浅的灰色像素与黑色像素混淆。因此,我引入了一个阈值。

主要问题似乎是您交换了 xy

我清理了一些格式 (PEP8)。

下面的代码在您的测试图像(保存为 JPG)上运行良好。

import PIL
from PIL import Image

threshold = 220 # Everything below threshold is considered black.

bw = Image.open('abw.jpg')
width, height = bw.size
top = bottom = left = right = None
for y in range(height):
    for x in range(width):
        if bw.getpixel((x,y)) < threshold:
            # if black-ish pixel is found
            if (left is None) or (x < left):
                left = x
            if (right is None) or (x > right):
                right = x
            if (top is None) or (y < top):
                top = y
            if (bottom is None) or (y > bottom):
                bottom = y

im = bw.crop((left, top, right + 1, bottom + 1))
im.show()