Python ndimage:将现有的ndarray转换为灰度

时间:2017-05-26 16:21:17

标签: python python-2.7 scipy ndimage

在我的python 2.7探索尝试使用scipy期间,我制作了以下简单脚本:

#!/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()

对图像(例如bluring和greayscale)进行简单处理。我设法从已加载的图像中进行模糊,但是如何进行灰度?

我找到的最接近的是How can I convert an RGB image into grayscale in Python?但他们没有使用ndimage提供解决方案。

此外,ndimage可以在打开期间转换,而不是使用已打开的图像。

我还尝试使用http://ebanshi.cc/questions/108516/convert-rgb-image-to-grayscale-in-python

中的方法实现方法greyscale
def grayscale(imgData):
    r=imgData[:,:,0]
    g=imgData[:,:,1]
    b=imgData[:,:,2]
    return  r * 299. / 1000 + g * 587. / 1000 + b * 114. / 1000

但是我收到以下错误:

  

追踪(最近一次通话):     文件“/home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py”,第83行,       主要()     文件“/home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py”,第78行,主要       saveImage(saveImagePath,processedData)     在saveImage中输入文件“/home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py”,第52行       im.save(路径)     文件“/usr/lib/python2.7/dist-packages/PIL/Image.py”,第1675行,保存       save_handler(self,fp,filename)     文件“/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py”,第682行,在_save中       提高IOError(“无法将模式%s写为PNG”%模式)   IOError:无法将模式F写为PNG

任何想法?

2 个答案:

答案 0 :(得分:2)

Dimitris解决方案不起作用,因为您尝试使用无效模式保存文件。 F用于32位浮点像素,当您调用saveImage时,图像数据仍处于F模式。您可以在print im.mode函数中添加以下行saveImage来自行检查。

有关PIL库的所有模式,请参阅http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes

要解决此问题,您只需在保存前调用convert('RGB')即可将图像数据再次转换为RGB模式。

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

答案 1 :(得分:0)

最后我需要创建自己的功能。这并不难:

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