I'm working on a program which applies a median blur onto a multiframe tiff file. My goal is to filter through every frame in the tiff sequence and then save the result as the same sequence, just filtered. However, anytime I run it, it only saves the last frame, as I don't know how to properly save the data into a separate sequence as it runs.
#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)
On Andrews advice, the code was modified to look like this:
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
So now it works perfectly fine!