Python:多次滚动数组并将每次迭代保存为图像

Python: rolling an array multiple times and saving each iteration as an image

我正在使用 for 循环获取多张图像。我想通过在 x 和 y 中将初始图像滚动一个像素并每次保存滚动图像来为每个图像获得 5 个伪层。

我正在练习一张图片以确保我可以从中得到五层,但我并不高兴。

我的代码在下面,但它只保存了第一张图片;输出是 pl_0.tif

list_frames = glob.glob('*.gif')
for index, fname in enumerate(list_frames):
    im = Image.open(fname)
    shift=1
    imary0 = np.array(im) # initial image (first layer)
    imary1x = np.roll(imary0, shift, axis=0) # shift image by one pixel to create second layer
    imary1xy = np.roll(imary1x, shift, axis=1)
    imary2x = np.roll(imary1xy, shift, axis=0) # shift previous image again to create third layer
    imary2xy = np.roll(imary2x, shift, axis=1)
    imary3x = np.roll(imary2xy, shift, axis=0) # shift previous image again to create fourth layer
    imary3xy = np.roll(imary3x, shift, axis=1)
    imary4x = np.roll(imary3xy, shift, axis=0) # shift previous image again to create fifth layer
    imary4xy = np.roll(imary4x, shift, axis=1)
    im0 = Image.fromarray(imary0)
    im0.save('pl_{}.tif'.format(index))
    im1 = Image.fromarray(imary1xy)
    im1.save('pl_{}.tif'.format(index))
    im2 = Image.fromarray(imary2xy)
    im2.save('pl_{}.tif'.format(index))
    im3 = Image.fromarray(imary3xy)
    im3.save('pl_{}.tif'.format(index))
    im4 = Image.fromarray(imary4xy)
    im4.save('pl_{}.tif'.format(index))
    im.close()

有什么建议吗? (如果这是一个简单的修复,请随时嘲笑我)

您将所有 5 张图像保存在同一个输出文件中,这意味着您只得到一张图像,im4

im0.save('pl_{}.tif'.format(index))
im1 = Image.fromarray(imary1xy)
im1.save('pl_{}.tif'.format(index))
im2 = Image.fromarray(imary2xy)
im2.save('pl_{}.tif'.format(index))
im3 = Image.fromarray(imary3xy)
im3.save('pl_{}.tif'.format(index))
im4 = Image.fromarray(imary4xy)
im4.save('pl_{}.tif'.format(index))

(注意索引直到下一次循环才被修改)

快速修复:

im0.save('pl_{}0.tif'.format(index))
im1 = Image.fromarray(imary1xy)
im1.save('pl_{}1.tif'.format(index))
im2 = Image.fromarray(imary2xy)
im2.save('pl_{}2.tif'.format(index))
im3 = Image.fromarray(imary3xy)
im3.save('pl_{}3.tif'.format(index))
im4 = Image.fromarray(imary4xy)
im4.save('pl_{}4.tif'.format(index))

未经测试,但我认为这应该符合您的目标:

添加一个 number_of_shifts 变量,然后使用它进行迭代。然后对 np.roll 的调用是嵌套的,我认为这应该有效

list_frames = glob.glob('*.gif')
for index1, fname in enumerate(list_frames):
    im = Image.open(fname)
    shift=1
    number_of_shifts = 4
    image_list = []
    imary0 = np.array(im) # initial image (first layer)
    for _ in range(number_of_shifts):
        if not image_list:
            image_list.append(imary0)
        else:
            image_list.append(np.roll(np.roll(image_list[-1], shift, axis=0), shift, axis=1))
    for index2, img in enumerate(image_list):
        img.save("pl_{}_{}.tif".format(fname, index2))
    im.close()