Using numpy to efficiently convert 16-bit image data to 8 bit for display, with intensity scaling

前端 未结 5 1984
耶瑟儿~
耶瑟儿~ 2020-12-15 09:55

I frequently convert 16-bit grayscale image data to 8-bit image data for display. It\'s almost always useful to adjust the minimum and maximum display intensity to highlight

5条回答
  •  悲&欢浪女
    2020-12-15 10:06

    This is the answer I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

    Basically for converting from uint16 to uint8 algorithm looks like this

    a = (255 - 0) / (65535 - 0)
    b = 255 - a * 65535
    newvalue = (a * img + b).astype(np.uint8)
    

    A generalized version would look like this

    def convert(img, target_type_min, target_type_max, target_type):
        imin = img.min()
        imax = img.max()
    
        a = (target_type_max - target_type_min) / (imax - imin)
        b = target_type_max - a * imax
        new_img = (a * img + b).astype(target_type)
        return new_img
    

    e.g.

    imgu8 = convert(img16u, 0, 255, np.uint8)

提交回复
热议问题