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

时间:2015-08-29 15:24:40

标签: python image python-imaging-library

我试图编写一个python程序来裁剪图像以删除多余的空白区域。为此,我遍历整个图像以查找最左侧,最右侧,最顶部和最底部像素,以识别裁剪所需的边界。我的代码错过了左边,右边和底边的一些像素。给出的第一个图像是源图像,另一个是结果图像。

enter image description here

enter image description here

这是我的代码:

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')

有人可以在我的代码中找出问题吗?

1 个答案:

答案 0 :(得分:1)

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

主要问题似乎是您交换了 x y

我清理了一些格式(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()