Converting RGBA image to Gray scale and then binary

Hi,

I need to convert a RGBA image in to Gray scale and then to binary with a threshold but I am not able to do that in python. Here is my code . The error which I get is “AttributeError: module ‘PIL.Image’ has no attribute ‘rgb2gray’”

# Import libraries 
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

# Reading an Image
image = Image.open('Board1_1.png')
image_gray = Image.rgb2gray(image)

Hi,

According to this you can use image_gray = image.convert(‘LA’).

Other libraries like skimage or scipy call this functionality rgb2gray but the PIL library you use does not.

What is the difference between the arguments ‘L’ and ‘LA’ inside the function image.convert ?

When I convert the image to gray scale using the argument ‘LA’, I get the dimension of the gray scale image is rows x col x 2 which I don’t understand why there are still two matrix instead of one matrix

LA mode has luminosity (brightness) and alpha

Maybe you want only ‘L’.

I have used the argument ‘LA’ and get the gray scale image which I plotted. I don’t know why only ‘L’ does not work as I get dark image.

image_gray = image.convert('LA')

The gray scale image has two dimension i.e., two matrix (row x col x 2). I can plot it, it looks like a gray scale image. Now I need to binarize it with threshold and plot a histogram. I know the theory but could not find the which function in python can convert gray scale image to binary and then make its histogram.

I have tried this function
'(thresh, im_bw) = cv2.threshold(image_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

I get this error

cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function ‘threshold’
Overload resolution failed:

  • src is not a numpy array, neither a scalar
  • Expected Ptrcv::UMat for argument ‘src’

FWIW, PIL.ImageOps has a grayscale function. It takes an image and returns an image.

>>> help(PIL.ImageOps.grayscale)
Help on function grayscale in module PIL.ImageOps:

grayscale(image)
    Convert the image to grayscale.
    
    :param image: The image to convert.
    :return: An image.

It’s not an object interface, but I wouldn’t be surprised if it was wrapped somewhere in an object-oriented API. Figuring that out is left as an exercise for the reader.