Skip to main content
 首页 » 编程设计

python ndimage : Converting an existing ndarray into greyscale

2024年10月01日9shangdawei

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

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

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

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

ndimage 也可以在打开期间进行转换,而不是使用已经打开的图像。

我还尝试实现 greyscale 方法,如 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 

但是我得到以下错误:

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

有什么想法吗?

请您参考如下方法:

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

参见 http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes对于 PIL 库中的所有模式

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

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