我想将图片2.jpeg
的大小调整为28 * 28像素,并且我使用模块PIL
来调整此图片的大小:
我创建了这个类:
from PIL import Image
import PIL
import numpy
from resizeimage import resizeimage
import scipy.misc
''' This class is to resize input image to MNIST size (28x28 px) '''
class Resize_img:
def __init__(self, imageName):
print 'Image -- ', imageName
self.resized_image = ''
# resize img to mnist size [28x28]
with open(imageName,'r+b') as f:
with Image.open(f) as image:
cover = resizeimage.resize_cover(image, [28, 28])
self.resized_image = 'new ' + imageName
cover.save(self.resized_image, image.format)
# transform img to MNIST form
# image to ndarray
PILimg = PIL.Image.open(self.resized_image)
self.mnist_image_input = scipy.misc.fromimage(PILimg,
True) # True => space gray! ----------------------------------------------------
self.mnist_image_input = (numpy.multiply(self.mnist_image_input,
1.0 / 255.0) - 1.0) * -1.0 # inverse the image :D ( white -> dark )
def main(): # To test this Class.
imageTest = '/home/brm17/Desktop/Myapp/2.jpeg' # The name of the image to resize
imageTest = Resize_img(imageTest)
scipy.misc.imshow(imageTest.mnist_image_input)
if __name__ == "__main__":
main()
# sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
如果我运行此脚本,终端打印:
Image -- /home/brm17/Desktop/Myapp/2.jpeg
Traceback (most recent call last):
File "Resize_img.py", line 40, in <module>
main()
File "Resize_img.py", line 35, in main
imageTest = Resize_img(imageTest)
File "Resize_img.py", line 18, in __init__
with Image.open(f) as image:
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 528, in __getattr__
raise AttributeError(name)
AttributeError: __exit__
问题是什么,以及如何解决这个问题?
答案 0 :(得分:2)
您似乎正在使用with
语句,而对象没有__exit__
方法。只是不要使用with语句:
image = Image.open(f)
cover = ...
答案 1 :(得分:1)
是的!
将with Image.open(f) as image:
更改为image = Image.open(f)
。
它修好了。