Intensity normalization of image using Python+PIL - Speed issues

前端 未结 2 1136
甜味超标
甜味超标 2021-01-04 23:47

I\'m working on a little problem in my sparetime involving analysis of some images obtained through a microscope. It is a wafer with some stuff here and there, and ultimatel

相关标签:
2条回答
  • 2021-01-05 00:09
    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(FILENAME).convert('RGBA')
        arr = np.array(img)
        new_img = Image.fromarray(normalize(arr).astype('uint8'),'RGBA')
        new_img.save('/tmp/normalized.png')
    
    0 讨论(0)
  • 2021-01-05 00:14

    See http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.fromimage.html#scipy.misc.fromimage

    You can say

    databack = scipy.misc.fromimage(pixback)
    rmax = numpy.max(databack[:,:,0])
    gmax = numpy.max(databack[:,:,1])
    bmax = numpy.max(databack[:,:,2])
    

    which should be much faster than looping over all (r,g,b) triplets of your image. Then you can do

    dataold = scip.misc.fromimage(pixold)
    r = dataold[:,:,0] / (pixback[:,:,0] * rmax )
    g = dataold[:,:,1] / (pixback[:,:,1] * gmax )
    b = dataold[:,:,2] / (pixback[:,:,2] * bmax )
    
    datanew = numpy.array((r,g,b))
    imnew = scipy.misc.toimage(datanew)
    

    The code is not tested, but should work somehow with minor modifications.

    0 讨论(0)
提交回复
热议问题