2011-09-28 121 views
0

让我们假设图像存储为一个PNG文件,我需要放下每一个奇数行,并将结果水平调整为50%,以保持纵横比。如何在Python中对图像进行隔行扫描?

结果必须有原始图像分辨率的50%。

它不足以推荐像PIL这样的现有图像库,我希望看到一些工作代码。

UPDATE - 即使这个问题收到了正确的答案,我想提醒其他人PIL是不是一个伟大的形状,在项目网站没有更新的几​​个月,有一个bug traker和无链接列表活动相当低。我惊讶地发现用PIL保存的一个简单的BMP文件没有被PIL加载。

+0

让我明确 - 你在问如何使用PIL来做到这一点?或者你问如何在没有PIL的情况下做到这一点? –

+1

看起来像PIL的“im.transform”可能会有用。如果没有,就有'im.resize',你可以对其余的像素级操作。你有5100代表和金徽章,所以我认为你可以从那里拿走。 –

+0

PIL没问题,我更新了问题。我正在寻找一些工作代码,为其他人记录程序。我确信我自己可以编写代码,但我无聊回答自己的问题。 – sorin

回答

1

是它必须保持每一个偶数行(其实,定义“偶” - 你从10计数为图像的第一行)

如果你不介意这行是下降,使用PIL:

from PIL import Image 
img=Image.open("file.png") 
size=list(img.size) 
size[0] /= 2 
size[1] /= 2 
downsized=img.resize(size, Image.NEAREST) # NEAREST drops the lines 
downsized.save("file_small.png") 
+0

This因为'resize'的默认过滤器是'NEAREST',它会抛弃所有其他像素。 +1为一个非常简单的解决方案。 –

+0

感谢马克 - 我应该提到我使用'NEAREST'默认。 –

0

我最近想对一些立体图像进行去隔行处理,提取左眼和右眼的图像。对于我这样写道:

from PIL import Image 

def deinterlace_file(input_file, output_format_str, row_names=('Left', 'Right')): 
    print("Deinterlacing {}".format(input_file)) 
    source = Image.open(input_file) 
    source.load() 
    dim = source.size 

    scaled_size1 = (math.floor(dim[0]), math.floor(dim[1]/2) + 1) 
    scaled_size2 = (math.floor(dim[0]/2), math.floor(dim[1]/2) + 1) 

    top = Image.new(source.mode, scaled_size1) 
    top_pixels = top.load() 
    other = Image.new(source.mode, scaled_size1) 
    other_pixels = other.load() 
    for row in range(dim[1]): 
     for col in range(dim[0]): 
      pixel = source.getpixel((col, row)) 
      row_int = math.floor(row/2) 
      if row % 2: 
       top_pixels[col, row_int] = pixel 
      else: 
       other_pixels[col, row_int] = pixel 


    top_final = top.resize(scaled_size2, Image.NEAREST) # Downsize to maintain aspect ratio 
    other_final = other.resize(scaled_size2, Image.NEAREST) # Downsize to maintain aspect ratio 
    top_final.save(output_format_str.format(row_names[0])) 
    other_final.save(output_format_str.format(row_names[1])) 

output_format_str应该是这样的:"filename-{}.png"其中{}将与该行的名称来代替。

请注意,它最终的图像是原始大小的一半。如果你不想要这个,你可以旋转最后的缩放步骤

它不是最快的操作,因为它逐个像素地穿过,但我看不到从图像中提取行的简单方法。

相关问题