from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

img1 = Image.open('multipage.tif')

# The following approach seems to be having issue with the 
# current TIFF format data

print('The size of each frame is:')
print(img1.size)

# Plots first frame
print('Frame 1')
fig1 = plt.figure(1)
img1.seek(0)
# for i in range(250):
    # pixA11 = img1.getpixel((1,i))
    # print(pixA11)
f1 = list(img1.getdata())


# Plots eleventh frame
# print('Frame 11')
# fig2 = plt.figure(2)
# img1.seek(10)
# # for i in range(250):
    # # pixB11 = img1.getpixel((1,i))
    # # print(pixB11)
# f2 = list(img1.getdata())
# print(f2[10000])
# plt.imshow(img1)
# fig2.show()
# input()

# Create a new image
fig3 = plt.figure(3)
imgAvg = Image.new(img1.mode, img1.size)
print(img1.mode)
print(img1.size)
fAvg = list()
pix = imgAvg.load()
for i in range(512):
    for j in range(512):
        pixVal = (f1[i*512+j] + f1[i*512+j]) / 2
        # fAvg.append(pixVal)
        fAvg.insert(i*512+j,pixVal)
imgAvg.putdata(fAvg)
imgAvg.save('avg.tiff')
plt.imshow(imgAvg)
fig3.show()
print('Average')


# The following is necessary to keep the above figures 'alive'
input()



# data = random.random((256, 256))
# img1 = Image.fromarray(data)
# img1.save('test.tiff')
print(f1[1000])
plt.imshow(img1)
fig1.show()
input()