图像强度归一化Intensity normalization

#因为opencv读入的图片矩阵数值是0到255,有时我们需要对其进行归一化为0~1
'''
import cv2
img3 = cv2.imread('me.png')
img3 = img3.astype("float") / 255.0  #注意需要先转化数据类型为float
cv2.imshow("Image",img3)
cv2.waitKey()
print(img3.dtype)
print(img3)
'''
import numpy as np
from PIL import Image

def normalize(arr):
    """
    Linear normalization
    http://en.wikipedia.org/wiki/Normalization_%28image_processing%29
    """
    arr = arr.astype('float')
    # Do not touch the alpha channel
    for i in range(3):
        minval = arr[...,i].min()
        maxval = arr[...,i].max()
        if minval != maxval:
            arr[...,i] -= minval
            arr[...,i] *= (255.0/(maxval-minval))
    return arr

def demo_normalize():
    img = Image.open('happy1.png').convert('RGBA')
    arr = np.array(img)
    new_img = Image.fromarray(normalize(arr).astype('uint8'),'RGBA')
    new_img.save('./normalized.png')
demo_normalize()	

 

你可能感兴趣的:(机器学习,Tensorflow,python3)