'How to convert image into array?
When I import the keras dataset mnist, I get x_train elements like the following:
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()
How can I take any image and force it into these same dimensions (28x28) with grayscale intensity?
I've tried
from PIL import Image
from numpy import asarray
img = Image. open(r'<my_dir>\test.jpg')
resized_img = img. resize((28,28))
x = asarray(resized_img)
x
But that doesn't appears to get the shape (28, 28, 3) and I'm looking for a shape (28,28).
Solution 1:[1]
I was able to use the following code to accomplish this:
from PIL import ImageFilter
from PIL import Image
import matplotlib.pyplot as plt
def imageprepare(argv):
im = Image.open(argv).convert('L')
width = float(im.size[0])
height = float(im.size[1])
newImage = Image.new('L',(28,28),(255))
if width > height:
nheight = int(round((28.0 / width * height),0))
if (nheight == 0):
nheight = 1
img = im.resize((28,28), Image.ANTIALIAS).filter(ImageFilter.SHRPEN)
wtop = 0
newImage.paste(img,(0,wtop))
else:
nwidth = int(round((28.0/height*width),0))
if (nwidth == 0):
nwidth = 1
img = im.resize((28,28), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wleft = 0
newImage.paste(img,(wleft,0))
tv = list(newImage.getdata())
tva = tv #[(255 - x) * 1.0 / 255.0 for x in tv]
return tva
x=[imageprepare(r'<my_dir>\test.jpg')]
newArr=[[0 for d in range(28)] for y in range(28)]
k = 0
for i in range(28):
for j in range(28):
newArr[i][j]=x[0][k]
k = k+1
plt.imshow(newArr,interpolation='nearest')
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark McGown |


