将中值模糊结果导出到 class 并导出到 TIFF

Exporting results of median blur into a class and exporting to TIFF

我正在开发一个将中值模糊应用于多帧 tiff 文件的程序。我的目标是过滤 tiff 序列中的每一帧,然后将结果保存为相同的序列,只是过滤。然而,任何时候我 运行 它,它只保存最后一帧,因为我不知道如何正确地将数据保存到单独的序列中,因为它 运行s.

#takes .tiff, loads it into PIL, converts to greyscale, sets attributes in PIL form
im = Image.open('example_recording.tif').convert('L')
im.save('greyscale_example.tif')

width,height = im.size
image_lookup = 0

#creates class used to de-sequence the animation


class ImageSequence:
    def __init__(self, im):
        self.im = im
    def __getitem__(self, ix):
        try:
            if ix:
                self.im.seek(ix)
            return self.im
        except EOFError:
            raise IndexError # end of sequence; needed to avoid process from unecessary breaking once it runs to the end of the tiff file animation


for frame in ImageSequence(im):
            imarray = np.array(frame)
            Blur = cv2.medianBlur(imarray,5)
            im = Image.fromarray(Blur)

im.save('corrected.tif')
#(saves actually only the last frame of the movie, med-corrected)

根据 Andrews 的建议,将代码修改为如下所示:

im = Image.open('example_recording.tif')
width,height = im.size
image_lookup = 0
n = 1
while True:
    try:
        im.seek(n)
        n = n+1
    except EOFError:
        print "length is",  n
        break;
    #this solves the length issue as ImageSequence doesnt have _len_ attribute
class ImageSequence:
    def __init__(self, im):
        self.im = im
    def __getitem__(self, ix):
        try:
            if ix:
                self.im.seek(ix)
            return self.im
        except EOFError:
            raise IndexError
depth = n
target_array = np.zeros((width, height, depth))
for index, frame in enumerate(ImageSequence(im)):
    imarray = np.array(frame)
    Blur = cv2.medianBlur(imarray,5)
    print type(Blur)
    im = Image.fromarray(Blur)
    im.save('corrected_{}.tif'.format(index))
    print n

所以现在它工作得很好!

depth = len(ImageSequence(im))
target_array = np.zeros((width, height, depth))
for index, frame in enumerate(ImageSequence(im)):
    imarray = np.array(frame)
    Blur = cv2.medianBlur(imarray,5)
    target_array[:, :, index] = Blur

这给了你一个很好的矩阵数组,我认为你必须颠倒你所做的一切来拉出你的图像,但我不是 PIL 专家。

编辑:

for index, frame in enumerate(ImageSequence(im)):
    imarray = np.array(frame)
    Blur = cv2.medianBlur(imarray,5)
    im = Image.fromarray(Blur)
    im.save('corrected_{}.tif'.format(index))

这应该至少为每个循环提供一个图像。