在尝试使用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可以在打开过程中进行转换,而不使用已打开的图像。
我还尝试用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
但我收到以下错误:
追溯(最近一次通话):
在第83行的文件“ /home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py”
主要()
在主文件中的文件“ /home/pcmagas/Kwdikas/python/Basic/scripy/scipy_image_examples.py”
saveImage(saveImagePath,已处理数据)
在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,文件名)
_save中的文件“ /usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py”,第682行
引发IOError(“无法将模式%s写入为PNG”%模式)
IOError:无法将模式F编写为PNG
有任何想法吗?
最佳答案
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