Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10048

Python ndimage: Converting an existing ndarray into greyscale

During my python 2.7 exploration trying to use scipy I have made the following simple script:

#!/usr/bin/env python
# coding=utf-8
# -*- Mode: python; c-basic-offset: 4 -*-

from scipy import ndimage
import numpy as np
from scipy import misc
import argparse
import Image

def getArguments():
    parser = argparse.ArgumentParser(description="An simple Image processor")
    parser.add_argument('image_file', metavar="FILENAME", type=str,
                        help="The image file that will be read In order to be processed")
    return parser.parse_args()


def getImagePathFromArguments():
    '''
    :return: string
    '''
    args = getArguments()
    return args.image_file


def loadImage(image):
    '''
    :param image: The path of the Image
    :return: 
    '''
    return misc.imread(image)


def grayscale(imgData):
    #Greyscale action done here
    pass


def blur(imgData):
    '''
    :param nparray imgData: 
    :return: 
    '''
    return ndimage.gaussian_filter(imgData, 1)

def saveImage(path, imgData):
    im = Image.fromarray(imgData)
    im.save(path)


def main():
    imagePath = getImagePathFromArguments()
    print "Loading Image from %s" % (imagePath,)
    image = loadImage(imagePath)

    while True:

        print "Select \n"
        print "1. Greyscale"
        print "2. Bluring"
        option = int(raw_input("Please do your option: "))

        if (option != 1 and option != 2):
            print "Wrong Option"
        else:
            processedData=0
            if option == 1:
                processedData = grayscale(image)
            elif option == 2:
                print "Bluring Image"
                processedData = blur(image)

            saveImagePath = raw_input("Where to you want to store the image?")
            saveImage(saveImagePath, processedData)
            break


if __name__ == "__main__":
    main()

That does simple process on images such as bluring and greayscale. I managed to do the blur from an already loaded image but how about greyscale?

The closest I found is How can I convert an RGB image into grayscale in Python? But they do not provide a solution using the ndimage.

Also ndimage can convert during opening and not using an already opened image.

I also tried to implement the method greyscale with as seen in http://ebanshi.cc/questions/108516/convert-rgb-image-to-grayscale-in-python:

def grayscale(imgData):
    r=imgData[:,:,0]
    g=imgData[:,:,1]
    b=imgData[:,:,2]
    return  r * 299. / 1000 + g * 587. / 1000 + b * 114. / 1000

But I get the following error:

Traceback (most recent call last): File "/home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py", line 83, in main() File "/home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py", line 78, in main saveImage(saveImagePath, processedData) File "/home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py", line 52, in saveImage im.save(path) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1675, in save save_handler(self, fp, filename) File "/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 682, in _save raise IOError("cannot write mode %s as PNG" % mode) IOError: cannot write mode F as PNG

Any Ideas?

Upvotes: 2

Views: 1048

Answers (2)

Fanis Despoudis
Fanis Despoudis

Reputation: 386

Dimitris you solution does not work because you are trying to save a file with an invalid mode. F is for 32 bit floating point pixels and when you call saveImage the image data are still in F mode. You can check by yourself by adding the line: print im.mode in the saveImage function.

See http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes for all modes on the PIL library

To fix that you just need to convert the image data to RGB mode again by calling convert('RGB') before saving.

http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.convert

Upvotes: 2

Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10048

In the end I needed to create my own function. It was not that hard:

def grayscale(imgData):
    r=imgData[:,:,0]
    g=imgData[:,:,1]
    b=imgData[:,:,2]
    return  r/3 + g /3 + b/3

Upvotes: 0

Related Questions