我有多个图像,我正在使用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()
有什么建议吗? (如果这是一个简单的解决方案,请随意嘲笑我)
答案 0 :(得分:1)
您将所有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))
(注意在下一个循环之前不会修改索引)
的quickfix:
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))
答案 1 :(得分:1)
未经测试,但我认为这应该符合您的目标:
添加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()