s900n
s900n

Reputation: 3375

Python: Converting tiff to numpy array only gives values with 0 and 255

I want to read multipage .tiff files, convert to grayscale and store as numpy array. My Code:

from PIL import Image, ImageOps ,ImageSequence
import numpy as np 

im = Image.open("GL.tif")
pages = {}
for i, page in enumerate(ImageSequence.Iterator(im)):
    page = ImageOps.grayscale(page)
    pages[i] = np.array(page, dtype='uint8')

When I print the resulting numpy array the values are only 0 and 255. This results as a loss in image quality.

Sample output array:

print(pages[0])

[[  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]
 [  0 255 255 ...   0   0   0]
 ...
 [  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]]

I need the image intensities between 0 and 255. Thanks for help=)

Upvotes: 0

Views: 1451

Answers (2)

andre_bsb
andre_bsb

Reputation: 41

I work a lot with GIS and .tiff files are vey common. In my experience .tiif files seems to be a difficult format to work with outside osgeo module. I've seen people working with it with PIL.Image, but also have seen people getting erros like "file type not supported" whenever they tried to load a .tiff file.

Might not be for your case, but if you're working with RGB images converting it to a numpy array using osgeo.gdal might avoid errors. Here's the code if you would like to try:

import numpy as np
from osgeo import gdal

dataset = gdal.Open(tiff_file_path)
num_channels = dataset.RasterCount


band1 = dataset.GetRasterBand(1) # Red channel
band2 = dataset.GetRasterBand(2) # Green channel
band3 = dataset.GetRasterBand(3) # Blue channel

b1 = band1.ReadAsArray()
b2 = band2.ReadAsArray()
b3 = band3.ReadAsArray()

img_np = np.dstack((b1, b2, b3))

Upvotes: 1

programandoconro
programandoconro

Reputation: 2709

Please try this, it should give you the intensities:

from PIL import Image
import numpy as np 

im = Image.open("GL.tif")

data = np.asarray(im)

np.set_printoptions(threshold=np.inf, linewidth=140)

for i in data:
    print(i)

Using np.set_printoptions allows you to see all the values. Then you can save them to a dictionary as you were doing.

Upvotes: 0

Related Questions