regarding displaying and saving 0-1 ndarrays into images - python

There exist a ndarray with shape (5508,1,64,80), which stores 5508 two dimensional 0-1 array corresponding to 5508 images. I am trying to save them into 5508 images with the following code segment.
import numpy as np
import os
image_path = "/data/image_test"
import matplotlib.pyplot as plt
import matplotlib.cm as cmp
if __name__ == '__main__':
img_array = np.load('/data/imgs_mask_test.npy')
print(img_array.shape)
for i in range(img_array.shape[0]):
file_name = os.path.join(image_path,'_'+str(i)+'.png')
plt.imsave(file_name,img_array[i,0],cmap=cmp.gray)
I am not sure whether this code segment is right. I checked the generated images, which are all black. Does that mean all the values in the original ndarray are 0?From the perspective of numpy, can we get all the locations having entry value of 1?
Moreover, I am suspecting whether I need to re-scale this 0-1 to 0-255? But it seems to me that it will still just give me two values, e.g., 0 and 255.
The following is a just a screenshot from the windows file system.

Related

How to sort the images using one of the average pixels in python PIL

I'm on the way to sorting several images according to their average pixel values using PIL. In the below code I choose to pick up the average red value as the prameter to sort the images. The images are all in 640 x 480 RBG format. I have 10 images (from GRK_image1 to GRK_image10), instead of typing the code below 10 times, is there any faster way to loop through all the 10 images in one step and get all the average red values for each image? I have been stuck here for many days. Thank you!
from PIL import Image
import glob
# 1. Get the first picture, open it
first_image=Image.open('GRK_imge1.png')
all_pixels = []
for x in range(640):
for y in range(480):
R, G, B = first_image.getpixel((x,y))
all_pixels.append(R)
storeAllImages = []
AverageR = (sum(all_pixels)/len(all_pixels))
print(AverageR)
storeAllImages.append(('GRK_image1.png',AverageR))
print(storeAllImages)
I would use skimage to load all the files at once using some pattern - in my case all the files are cars1.jpg, car2.jpg, etc so I use 'car*.jpg'
This gives a list of 3d arrays, and I can take the mean of the red channel (the first of the 3 dimensions) as a key to sorted with the reverse=True flag to go from most red to least.
You can view some of them to make sure it's working, then save them, using enumerate to label.
import numpy as np
import matplotlib.pyplot as plt
from skimage.io import imread_collection, imshow, imsave
images = sorted(imread_collection("car*.jpg", conserve_memory=False),
key=lambda x: np.mean(x[:,:,0]),
reverse=True)
# to view your work
for i in images:
plt.figure()
plt.imshow(i)
# save images starting with most red
for c, i in enumerate(images):
imsave(f'most_red_{c}.jpg', i)

How can I take generate mean image of many 32x32 grayscale images in Python?

I have array are which is 50000x32x32. arr[i] stores the i-th grayscale image.
I want to compute the mean image of these images. I tried the following code(I got this code from stack overflow itself). This code was actually meant for RGB images.
I know, these changes of mine have a lot of mistakes, Apologies.
import os, numpy, PIL
from PIL import Image
# Access all PNG files in directory
allfiles=os.listdir(os.getcwd())
imlist=arr
N=len(imlist)
# Assuming all images are the same size, get dimensions of first image
w,h=Image.fromarray(imlist[0]).size
# Create a numpy array of floats to store the average (assume RGB images)
brr=numpy.zeros((h,w),numpy.float)
# Build up average pixel intensities, casting each image as an array of floats
for im in imlist:
imarr=numpy.array(Image.fromarray(im),dtype=numpy.float)
brr=brr+imarr/N
# Round values in array and cast as 8-bit integer
brr=numpy.array(numpy.round(arr),dtype=numpy.uint8)
# Generate, save and preview final image
out=Image.fromarray(brr,mode="L")
out.save("Average.png")
out.show()
Once you have your 5000 × 32 × 32 array, you can compute the mean image by using np.mean() with axis=0 (the first axis, which contains the collection of images). Let's make some random data:
import numpy as np
images = np.random.random((5000, 32, 32))
Now we can compute the mean image:
mean_image = images.mean(axis=0)
We can look at it with:
import matplotlib.pyplot as plt
plt.imshow(mean_image)
Which looks something like:

np.reshape(): Converting an image into a feature array based on rgb intensities

I am trying to segment a colour image using the Mean-Shift algorithm using sklearn.
I have the following code:
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from itertools import cycle
from PIL import Image
image = Image.open('sample_images/fruit_half.png')
image = np.array(image)
#need to convert image into feature array based on rgb intensities
flat_image = np.reshape(image, [-1,3])
I am trying to convert the image into a feature array based on rgb intensities so that I can do the clustering.
However, I get the following error:
ValueError: cannot reshape array of size 3979976 into shape (3)
I am not sure why I am getting this error and how I can resolve this. Any insights are appreciated.
It's because the image you're loading does not have RGB values (if you look at the dimensions, the last one is 4.
You need to first convert it to RGB like this:
image = Image.open('sample_images/fruit_half.png').convert('RGB')
image = np.array(image)
# Now it works
flat_image = np.reshape(image, [-1,3])

Python-Why does imshow() yield a blank image for a non-zero array?

My goal is to display a 2D Array as a image in Python. The array doesn't contain zero elements, and therefore I would expect an image in which imshow() automatically sets the color scale according to the array values. However, when I run the code, the image is blank.
The csv file is: https://ufile.io/urk5m
import numpy as np
import matplotlib.pyplot as plt
data_ = np.loadtxt(open("new_file.csv", "rb"), delimiter=",")
plt.imshow(data_)
My result is this: https://imgur.com/jMNnF0h
Always remember, but really always, that images works on 8bit integers. Thats why there is 2^8 shades of gray and why most commmon number of CS colors is (2^8)^3= 16.7 mil. colors. 3 because there are 3 color channels - RGB, each having 256 shades.
Everybody is counting with it and mainly the image processing libraries.
Therefore ALWAYS make sure you pass correct matrix datatype into image processing functions:
image_8bit = np.uint8(data_)
plt.imshow(image_8bit)
plt.show()

loading an image from cifar-10 dataset

I am using cifar-10 dataset for my training my classifier. I have downloaded the dataset and tried to display am image from the dataset. I have used the following code:
from six.moves import cPickle as pickle
from PIL import Image
import numpy as np
f = open('/home/jayanth/udacity/cifar-10-batches-py/data_batch_1', 'rb')
tupled_data= pickle.load(f, encoding='bytes')
f.close()
img = tupled_data[b'data']
single_img = np.array(img[5])
single_img_reshaped = single_img.reshape(32,32,3)
plt.imshow(single_img_reshaped)
the description of data is as follows:
Each array stores a 32x32 colour image. The first 1024 entries contain the red channel values, the next 1024 the green, and the final 1024 the blue. The image is stored in row-major order, so that the first 32 entries of the array are the red channel values of the first row of the image.
Is my implementation correct?
the above code gave me the following image:
I used
single_img_reshaped = np.transpose(np.reshape(single_img,(3, 32,32)), (1,2,0))
to get the correct format in my program.
Since Python uses the default C-like indexing order (row-major order), it can be forced to work in column-major order:
import numpy as np
import matplotlib.pyplot as plt
# I assume you have loaded your data into x_train (see some tutorial)
data = x_train[0, :] # get a row data
data = np.reshape(data, (32,32,3), order='F' ) # Fortran-like indexing order
plt.imshow(data)
single_img_reshaped = single_img.reshape(3,32,32).transpose([1, 2, 0])

Categories

Resources