Question

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

img=mpimg.imread('2048.png')

a = np.zeros_like(img)

for j in xrange(img.shape[0]):
    for i in xrange(img.shape[1]):
        a[j,i] = np.mean(img[j,i])

imgplot = plt.imshow(a)
plt.show()

This is what I have so far and it works, but it's very slow because it only edits 1 pixel at the time, what is a clever way of using arrays to make an image grey? And I can't use functions like convert("L").

Was it helpful?

Solution

In addition to unutbus answer, you might also want to take care when converting to grayscale: uniform weighting (taking the mean) is not the only, or necessarily correct, way to go.

From the wikipedia page

Y = 0.2126 R + 0.7152 G + 0.0722 B

which translates into

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

img = mpimg.imread('image.png')
arr = 0.2126* img[...,0] + 0.7152* img[...,1] + 0.0722 * img[...,2]
plt.imshow(arr, cmap=plt.get_cmap('gray'))
plt.show()

Note in response to question

The array is now stored in arr which you can now manipulate as you please.

Silhouette

If you need a silhouette / mask, you can use simple thresholding

bw = arr > 0.3
plt.imshow(bw)
plt.show()

No need to add in the colormap argument, though the default is jet, which will display as blue and red for a binary image.

Output

To save the image you can use plt.savefig which will use the colormap applied to the image. This means if you want a grayscale image you need to specify the 'gray' colormap

Alternatively using e.g. scipy.misc.imsave will save a 2d matrix as grayscale. Other libraries you could use include the png module

OTHER TIPS

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

img = mpimg.imread('image.png')
arr = img.mean(axis=-1)
plt.imshow(arr, cmap=plt.get_cmap('gray'))
plt.show()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top