2011-10-14 29 views
6

bu tekrarlanabilir örneği düşünün lütfen nesneleri:normalleştirmek numpy diziler

from PIL import Image 
import numpy as np 
import scipy.misc as sm 
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg 
import matplotlib.cbook as cbook 
import urllib 

datafile = cbook.get_sample_data('lena.jpg') 
lena_pil = Image.open(datafile) 
lena_pil_np = np.asarray(lena_pil) 

lena_scipy = sm.lena() 

lena_tmp = open('lena_tmp.png', 'wb') 
lena_tmp.write(urllib.urlopen('http://optipng.sourceforge.net/pngtech/img/lena.png').read()) 
lena_tmp.close() 

lena_mpl = mpimg.imread('lena_tmp.png') 

sm.info(lena_pil_np) 
sm.info(lena_scipy) 
sm.info(lena_mpl) 

Çıktı geçerli:

>>> sm.info(lena_pil_np) 
class: ndarray 
shape: (512, 512, 3) 
strides: (1536, 3, 1) 
itemsize: 1 
aligned: True 
contiguous: True 
fortran: False 
data pointer: 0xb707e01cL 
byteorder: little 
byteswap: False 
type: uint8 

>>> sm.info(lena_scipy) 
class: ndarray 
shape: (512, 512) 
strides: (2048, 4) 
itemsize: 4 
aligned: True 
contiguous: True 
fortran: False 
data pointer: 0xb6f7d008L 
byteorder: little 
byteswap: False 
type: int32 

>>> sm.info(lena_mpl) 
class: ndarray 
shape: (512, 512, 3) 
strides: (6144, 12, 4) 
itemsize: 4 
aligned: True 
contiguous: True 
fortran: False 
data pointer: 0xb6c7b008L 
byteorder: little 
byteswap: False 
type: float32 

nedenle tüm diziler farklı şekil ve tiptedir.

Ek işlemler için, bu dizilerin son değişken olarak lena.mpl olarak temsil edilmesini ya da dizi değerlerinin normalleştirilmiş [0..1] float32 türüne dönüştürülmesini istiyorum.

Bunu yapmanın en iyi yolu nedir?

cevap

5
def normalize(arr): 
    arr=arr.astype('float32') 
    if arr.max() > 1.0: 
     arr/=255.0 
    return arr