I've loaded an image using:
import numpy as np
from PIL import Image
imag = Image.open("image.png")
I = np.asarray(imag)
Where the shape of I is (951, 1200, 3)
But I would like to average each pixel roughly to it's luma values ((r*g*b)/3) to make the shape (951, 1200, 1).
What is the proper numpy operator to do this?
I think the easiest thing is to use Pillow's built-in conversion to Luminance as follows:
import numpy as np
from PIL import Image
# Load image and convert to luminance, and thence to Numpy array
imag = Image.open("image.png").convert('L')
I = np.asarray(imag)
Related
I would like to rescale and rotate image which I transform to numpy array with Pillow library (Image.open(..))
But i can use only numpy array manipulation.
Any tip or article how to do that? Without use of cv etc..
You can use PIL to resize and rotate like this
from PIL import Image
img = Image.open('Your/image/path')
img_120 = img.rotate(120)
img_re = img.resize((width, hight), Image.ANTIALIAS)
I have a 2d numpy.array object of dtype=uint16 representing a grayscale image. How do I save it to a PNG file and then read it back, obtaining the same array?
scikit-image makes this pretty easy:
from skimage.io import imread, imsave
import numpy as np
x = np.ones((100, 100), dtype=np.uint16)
imsave('test.png', x)
y = imread('test.png')
(x == y).all() # True
I have 5 pictures and i want to convert each image to 1d array and put it in a matrix as vector. I want to be able to convert each vector to image again.
img = Image.open('orig.png').convert('RGBA')
a = np.array(img)
I'm not familiar with all the features of numpy and wondered if there other tools I can use.
Thanks.
import numpy as np
from PIL import Image
img = Image.open('orig.png').convert('RGBA')
arr = np.array(img)
# record the original shape
shape = arr.shape
# make a 1-dimensional view of arr
flat_arr = arr.ravel()
# convert it to a matrix
vector = np.matrix(flat_arr)
# do something to the vector
vector[:,::10] = 128
# reform a numpy array of the original shape
arr2 = np.asarray(vector).reshape(shape)
# make a PIL image
img2 = Image.fromarray(arr2, 'RGBA')
img2.show()
import matplotlib.pyplot as plt
img = plt.imread('orig.png')
rows,cols,colors = img.shape # gives dimensions for RGB array
img_size = rows*cols*colors
img_1D_vector = img.reshape(img_size)
# you can recover the orginal image with:
img2 = img_1D_vector.reshape(rows,cols,colors)
Note that img.shape returns a tuple, and multiple assignment to rows,cols,colors as above lets us compute the number of elements needed to convert to and from a 1D vector.
You can show img and img2 to see they are the same with:
plt.imshow(img) # followed by
plt.show() # to show the first image, then
plt.imshow(img2) # followed by
plt.show() # to show you the second image.
Keep in mind in the python terminal you have to close the plt.show() window to come back to the terminal to show the next image.
For me it makes sense and only relies on matplotlib.pyplot. It also works for jpg and tif images, etc. The png I tried it on has float32 dtype and the jpg and tif I tried it on have uint8 dtype (dtype = data type); each seems to work.
I hope this is helpful.
I used to convert 2D to 1D image-array using this code:
import numpy as np
from scipy import misc
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
face = misc.imread('face1.jpg');
f=misc.face(gray=True)
[width1,height1]=[f.shape[0],f.shape[1]]
f2=f.reshape(width1*height1);
but I don't know yet how to change it back to 2D later in code, Also note that not all the imported libraries are necessary, I hope it helps
How to import RGB value of each pixel in an image to 1-D array?
I am using following thing:
from PIL import Image
im = Image.open("bride.jpg")
pix = im.load()
print pix[x,y]
this imports it into 2-D array which is not iterable.
I want this same thing but in 1-D array.
You can flatten the pixels into a 1D array as follows:
width, height = im.size
pixels = [pix[i, j] for i in range(width) for j in range(height)]
Easy if you're using numpy, and no need to load the image.
from PIL import Image
import numpy as np
im = Image.open("bride.jpg")
pix_flatiter = np.asarray(im).flat # is an iterable
If you want to load the whole array, you can do:
pix_flat = np.asarray(im).flatten() # is an array
I have a simple problem, but I cannot find a good solution to it.
I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps.
I can get a reasonable PNG output by using the pyplot.figure.figimage command:
dpi = 100.0
w, h = myarray.shape[1]/dpi, myarray.shape[0]/dpi
fig = plt.figure(figsize=(w,h), dpi=dpi)
fig.figimage(sub, cmap=cm.gist_earth)
plt.savefig('out.png')
Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this:
colored_PIL_image = magic_function(array, cmap)
Quite a busy one-liner, but here it is:
First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
Apply the colormap directly to myarray.
Rescale to the 0-255 range.
Convert to integers, using np.uint8().
Use Image.fromarray().
And you're done:
from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))
with plt.savefig():
with im.save():
input = numpy_image
np.uint8 -> converts to integers
convert('RGB') -> converts to RGB
Image.fromarray -> returns an image object
from PIL import Image
import numpy as np
PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:
import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')
np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.