0

Im trying to make a function which needs as input an image file in jpg format and outputs an array every time i call it. This is what i achieved so far:

import scipy.misc as sm
import numpy as np
from PIL import Image

def imagefunc(image):
    try:
        i = Image.open(image)
        if i.format == 'jpg':
            return i.format == 'jpg'
    except OSError:   # Checking for different possible errors in the input file
        print ('This is not a jpg image! Input has to be a jpg image!')
        return False 
    except FileNotFoundError:   # Another check for error in the input file
        print ('No image was found! Input file has to be in the same directory as this code is!')
        return False

    imgarray = np.array(sm.imread(image, True))
    return imgarray

The problem is that when i call it, "imagefunc(kvinna)" to open a jpeg picture it outputs: NameError: name 'kvinna' is not defined. What am i missing here? Is the code wrong or is it file directory problem? Thanks

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
JustANoob
  • 580
  • 1
  • 4
  • 19
  • try with `kvinna.jpeg` – bhansa Sep 18 '17 at 07:55
  • Make sure the directory of a image is same as your script. You also should use quotation marks and format when calling a function, so it should looke like this: `imagefunc('kvinna.jpg')` – JJAACCEeEKK Sep 18 '17 at 07:55
  • @JJAACCEeEKK, oh stupid me, that was the problem. Thanks alot. Now i understand why this question got a vote down lol – JustANoob Sep 18 '17 at 07:59

1 Answers1

1

Reading and Writing Images

You are not opening the image correctly, hence the Name Error

i = Image.open(image) # image should be "image_name.ext"

here image should be "kvinna.jpeg" with the extension.

so the function call will be: imagefunc("kvinna.jpeg") further check or either jpeg or jpg in your function definition.

Image.open(image) returns an Image object, later check the extension for it.

bhansa
  • 7,282
  • 3
  • 30
  • 55