2015-08-29 35 views
0

我试图编写一个python程序,它会裁剪图像以删除多余的空格。为此,我遍历整个图像以查找最左边,最右边,最上面和最下面的像素,以确定裁剪的必要边界。我的代码遗漏了左侧,右侧和底部边界上的一些像素。第一幅图像是源图像,另一幅是合成图像。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') 

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

+0

你想用for循环来实现什么?你能否详细说明一下吗? –

+0

For循环遍历图像并查找有用的边界值。正如你在这张图片中看到的那样,它周围没有多余的空白。 – user3566211

回答

1

您上传的图片是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() 
+0

谢谢。有效!但是,为什么你的权利和底部增加1? – user3566211

+0

因为我的印象是,最右边的列和最下面的行不包含在裁剪图像中。变量'bottom'将包含发现黑色像素的最低行的y坐标,并且它具有黑色像素的事实意味着您需要输出中的该行。 –

+0

好的,明白了。谢谢 – user3566211