Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 467
Ranveer Avatar asked Mar 25 '26 21:03

Ranveer


1 Answers

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.

like image 78
Ranveer Avatar answered Mar 28 '26 10:03

Ranveer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!