When I tried to convert the image to gray scale using:
from skimage.io import imread
from skimage.color import rgb2gray
mountain_r = rgb2gray(imread(os.getcwd() + '/mountain.jpg'))
#Plot
import matplotlib.pyplot as plt
plt.figure(0)
plt.imshow(mountain_r)
plt.show()
I got a weird colored image instead of a gray scale.
Manually implementing the function also gives me the same result. The custom function is:
def rgb2grey(rgb):
if len(rgb.shape) is 3:
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
else:
print 'Current image is already in grayscale.'
return rgb
Coloured image that is not in greyscale.
Why doesn't the function convert the image to greyscale?
Convert an Image to Grayscale in Python Using the Conversion Formula and the Matplotlib Library. We can also convert an image to grayscale using the standard RGB to grayscale conversion formula that is imgGray = 0.2989 * R + 0.5870 * G + 0.1140 * B .
Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.
You just have to take the average of three colors. Since its an RGB image, so it means that you have add r with g with b and then divide it by 3 to get your desired grayscale image. Its done in this way.
I = rgb2gray( RGB ) converts the truecolor image RGB to the grayscale image I . The rgb2gray function converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance. If you have Parallel Computing Toolbox™ installed, rgb2gray can perform this conversion on a GPU.
The resulting image is in grayscale. However, imshow
, by default, uses a kind of heatmap (called viridis) to display the image intensities. Just specify the grayscale colormap as shown below:
plt.imshow(mountain_r, cmap="gray")
For all the possible colormaps, have a look at the colormap reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With