Convert np.array of type float64 to type uint8 scaling values

后端 未结 3 1272
清酒与你
清酒与你 2020-12-07 22:40

I have a particular np.array data which represents a particular grayscale image. I need to use SimpleBlobDetector() that unfortunately only accepts 8bit images, so

3条回答
  •  温柔的废话
    2020-12-07 23:05

    Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

    img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

    However, if you don't want to use OpenCV, you can do this in numpy

    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
    

    And then use it like this

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

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

提交回复
热议问题