如何在Python中去交错图像?
假设我们有一张存储为png格式的图片,我需要去掉每一条奇数行,然后把结果的宽度缩小到原来的50%,这样才能保持图片的比例。
最终的图片分辨率必须是原始图片的一半。
光推荐一个现成的图像处理库,比如PIL,是不够的,我希望能看到一些实际的代码示例。
更新 - 即使这个问题得到了正确的回答,我还是想提醒大家,PIL的状态并不是很好,项目网站已经好几个月没有更新了,也没有链接到错误追踪器,活跃度也很低。我很惊讶地发现,使用画图保存的一个简单BMP文件居然无法被PIL加载。
2 个回答
1
我最近想要对一些立体图像进行去交错处理,也就是提取出左眼和右眼的图像。为此,我写了以下代码:
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"
这样的格式,其中的{}
会被行名替换。
需要注意的是,处理后的图像大小会变成原来的一半。如果你不想这样,可以调整最后的缩放步骤。
这个操作速度不是最快的,因为它是逐个像素处理的,不过我没有找到更简单的方法来从图像中提取行。
2
是否必须保留每一行偶数行(实际上,什么是“偶数”?你是从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")