如何在Python中对图像进行去隔行扫描?

时间:2011-09-28 12:55:09

标签: python image-processing python-imaging-library

假设图像存储为png文件,我需要删除每个奇数行并将结果水平调整为50%以保持纵横比。

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

推荐像PIL这样的现有图像库是不够的,我希望看到一些有效的代码。

更新 - 即使问题得到了正确答案,我也要警告其他人PIL状态不佳,项目网站几个月内没有更新,没有链接到错误跟踪器和列表活动非常低。我很惊讶地发现PIL没有加载用Paint保存的简单BMP文件。

2 个答案:

答案 0 :(得分:1)

保持每条偶数行是否必不可少(事实上,定义“偶数” - 您是从1还是0计算图像的第一行?)

如果您不介意删除哪些行,请使用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")

答案 1 :(得分: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",其中{}将替换为行名。

请注意,最终图像的大小为其原始大小的一半。如果你不想要这个,你可以改变最后的缩放步骤

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