Jericho Jones Jericho Jones - 3 months ago 24
Python Question

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

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!

Answer
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

That gives you a nice array of matrices, I would think you'll have to reverse everything you've done to pull your images out, but I'm not a PIL expert.

EDIT:

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))

This should give you an image for each loop, at least.

Comments