Ranveer
Ranveer

Reputation: 6863

Converting an RGB image to grayscale in Python

I am trying to convert an RGB image to grayscale using skimage in Python. Here's what I do:

for im_path in glob.glob(os.path.join(pos_raw, "*")):
    im = imread(im_path)
    im = color.rgb2gray(im)
    image_name = os.path.split(im_path)[1].split(".")[0] + ".pgm"
    image_path = os.path.join(pos_img_path, image_name)
    imwrite(image_path, im)

for a bunch of image files. My input image looks like this:

Color image

And the output image looks like this:

Black image

The expected output is this:

Gray image

What can be the issue here?

Upvotes: 3

Views: 7430

Answers (1)

Ranveer
Ranveer

Reputation: 6863

Figured it out. The problem was of contrast.

I printed out the image and saw that the values were all close to 0. I introduced a small line to stretch the contrast between 0 and 255 in the loop that made it work.

im = rescale_intensity(im, out_range=(0, 255))

Where rescale_intensity was imported from skimage.exposure.

Upvotes: 6

Related Questions