0

I'm a real beginner in python and I have a problem that I do not understand when I want to convert a RGB image into grayscale when I use advices I found in previous stakoverflow topic (How can I convert an RGB image into grayscale in Python?)

When I type this code everything works :

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])

im = mpimg.imread('test.gif') 
gray=rgb2gray(im)
plt.imshow(gray, cmap = plt.get_cmap('gray'))
plt.show()

So, I tried to creater a function so that I do not have to repeat all these lines if I want to convert other RGB images (I am not sure I should write return before the last line)

def load(fichier):
    im = mpimg.imread(fichier) 
    gray=rgb2gray(im)
    plt.imshow(gray, cmap = plt.get_cmap('gray'))
    plt.show()

It seems to work fine but I can't do :

load("test.gif")
File "<stdin>", line 5
load("test.gif")
       ^
SyntaxError: invalid syntax

I understand that the problem should be that "test.gif" is a string but is there an easy way to change my function so that it works ?

Thank you in advance for your help !

EDIT

I think it works now I do not undestand what I changed but it seems to work fine with that :

# -*-coding:utf-8 -*-``

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])

def load(fichier):
    im = mpimg.imread(fichier) 
    gray=rgb2gray(im)
    plt.imshow(gray, cmap = plt.get_cmap('gray'))
    return plt.show()

load('test.gif')
Community
  • 1
  • 1
Louise P
  • 51
  • 1
  • 9
  • 1
    I guess there is a syntax error right before the `load("test.gif")` call. Please, show us your entire code. – Delgan Apr 27 '17 at 12:21
  • `# -*-coding:utf-8 -*-`` import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from scipy.ndimage import imread from PIL import Image def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) im = mpimg.imread('test.gif') gray=rgb2gray(im) plt.imshow(gray, cmap = plt.get_cmap('gray')) plt.show() def load(fichier): im = mpimg.imread(fichier) gray=rgb2gray(im) plt.imshow(gray, cmap = plt.get_cmap('gray')) return plt.show() load('test.gif')` – Louise P Apr 27 '17 at 12:41
  • @Louise - instead of adding a comment, you should actually [edit] the question to add the extra information. Thanks! – Toby Speight Apr 27 '17 at 12:51

0 Answers0