Jack Ryan
Jack Ryan

Reputation: 21

RGB float image to grayscale uint8

I'm trying to create a function to convert an image from color to grayscale. Additionally, to turn it from float to integer.

I've noticed that by default, scikit-image conversion functions return images with floating-point representations in the range [0, 1]. I want an integer representation from 0-255 using np.uint8.

from skimage.color import rgb2gray
import numpy as np

def to_grayscale_uint (image):
    original = image()
    grayscale = rgb2gray(original)
    grayscale = np.uint8
    target = target.astype('uint8')
    return grayscale

Upvotes: 2

Views: 5189

Answers (1)

ndrplz
ndrplz

Reputation: 1644

As your ouput is in range [0, 1], you can simply multiply it by 255 and then use np.uint8() for casting.

import numpy as np

from skimage import data
from skimage.color import rgb2gray


def to_gray_uint(image):
    return np.uint8(rgb2gray(image) * 255)


original = data.astronaut()

gray = rgb2gray(original)
print(gray.min(), gray.max(), gray.dtype)  # prints: 0.0 1.0. float64

gray = to_gray_uint(original)
print(gray.min(), gray.max(), gray.dtype)  # prints: 0 255 uint8

Upvotes: 2

Related Questions