Search code examples
pythonimageimage-processingbarcodegrayscale

how to save an image in python variable and then change it to grayscale?


I need to do image processing for barcode. I know that I can save a picture and then load it in grayscale color_mode, but I dont want to load an image, instead I want to change the color of image into grayscale without saving or without having another image.

imag=Image.open('barcode.png')
w, h = imag.size
region = imag.crop((0, 20, w, h-150))
region.save("regions.png")  #I dont want to save this image 
img=image.load_img("regions.png",color_mode="grayscale")  #I want to do this work in a variable i.e. changing the color of image into grayscale without having a need of loading an image


Solution

  • Looks like you are using pillow.

    In pillow, you can do Image.convert()

    To convert to grayscale, do Image.convert('LA')

    The mode LA is combination of "8-bit pixels, black and white" and "alpha channel". See here for more about different available modes.


    Replace you code with the following:

    imag = Image.open('barcode.png')
    w, h = imag.size
    region = imag.crop((0, 20, w, h-150))
    img = region.convert('LA')