Reshape a numpy array from (x,x,1) to (x,x) - numpy

I want to reshape a numpy array from (32,32,1) to (32,32) so that I can plot an image of it using matplotlib.pyplot.imshow().
I'm getting an invalid dimensions error for matplotlib.pyplot.imshow(), so i assume it wants (32,32).
How can i reshape my numpy array to plot the image?

x.reshape([32,32])
np.squeeze(x)
x[:,:,0]
Any of those.

Related

Plotting a 3-dimensional numpy array

I have a 3d numpy array with the shape (128,128,384). Let's call this array "S". This array only contains binary values either 0s or 1s.
\now \i want to get a 3d plot of this array in such a way that \ I have a grid of indices (x,y,z) and for every entry of S when it is one \ I should get a point printed at the corresponding indices in the 3d grid. e.g. let's say I have 1 entry at S[120,50,36], so I should get a dot at that point in the grid.
So far I have tried many methods but have been able to implement one method that works which is extremely slow and hence useless in my case. that method is to iterate over the entire array and use a scatter plot. \here is a snippet of my code:
from numpy import np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
for i in range(0,128):
for j in range(0,128):
for k in range(0,384):
if S[i,j,k]==1:
ax.scatter(i,j,k,zdir='z', marker='o')
Please suggest to me any method which would be faster than this.
Also, please note that I am not trying to plot the entries in my array. The entries in my array are only a condition that tells me if I should plot corresponding to certain indices.
Thank you very much
You can use numpy.where.
In your example, remove the for loops and just use:
i, j, k = np.where(S==1)
ax.scatter(i,j,k,zdir='z', marker='o')

TensorFlow:Failed to convert a NumPy array to a Tensor (Unsupported object type int)

I am practicing on this kaggle dataset regarding car price prediction (https://www.kaggle.com/hellbuoy/car-price-prediction). I dont know why am I receiving this error.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow.keras import layers,models
cars_data=pd.read_csv('/content/CarPrice_Assignment.csv')
cars_data.head()
cars_data.info()
cars_data.describe()
train_data=cars_data.iloc[:103]
train_data=train_data.drop('price',axis=1)
train_data=np.asarray(train_data.values)
train_targets=cars_data.price.iloc[:103]
train_targets=np.asarray(train_targets)
test_data=cars_data.iloc[103:165]
test_data=test_data.drop('price',axis=1)
test_data=np.asarray(test_data.values)
test_targets=cars_data.price.iloc[103:165]
test_targets=np.asarray(test_targets)
val_data=cars_data.iloc[165:]
val_data=val_data.drop('price',axis=1)
val_data=np.asarray(val_data.values)
val_targets=cars_data.price.iloc[165:]
val_targets=np.asarray(val_targets)
model=models.Sequential()
model.add(layers.Dense(10,activation='relu',input_shape=(25,)))
model.add(layers.Dense(8,activation='relu'))
model.add(layers.Dense(6,activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer='rmsprop',loss='mse',metrics=['mae'])
model.fit(train_data,train_targets,epochs=20,batch_size=1)
There are 2 things you need to address in your code.
Categorical Variables
By printing the value of train_data, I can see there are still some categorical variables in form of string. Tensorflow cannot process that kind of data directly, so you need to deal with categorical variables. See answer from Best way to deal with categorical variables in regression problem - python as your starting point.
target shape
Your train_targets shape is (107,) means that this is a 1D array. The correct shape for tensorflow input(for simple regression problem) is (107,1). Modify your code like this to reshape the value :
train_targets=np.asarray(train_targets).reshape(-1,1)

how to convert flattened array of RGB image(1-D) back to original image

I have flattened 1D array of (1*3072) created from RGB image of dimension(32*32*3). I want to extract back the original RGB image of dimension(32*32*3) and plot it.
I have tried the solution suggested in how to convert a 1-dimensional image array to PIL image in Python
But it's not working for me, As it seems it is for a greyscale image
from PIL import Image
from numpy import array
img = Image.open("sampleImage.jpg")
arr = array(img)
arr = arr.flatten()
print(arr.shape)
#tried with 'L' & 'RGB' both
img2 = Image.fromarray(arr.reshape(200,300), 'RGB')
plt.imshow(img2, interpolation='nearest')
plt.show()
"Getting below error which expected because it is not able covert RGB"
ValueError: cannot reshape array of size 180000 into shape (200,300)
In order to interpret an array as an RGB image, it needs to have 3 channels. A channel is the 3rd dimension in the numpy array. So change your code to this:
img2 = Image.fromarray(arr.reshape(200,300,3), 'RGB')
I should mention that you talk about your flattened array being 1x3072, yet the example code seems to assume 200x300x3, which would be 1x180,000 when flattened. Which of these two is the truth, I couldn't tell you.

Slicing the channels of image and storing the channels into numpy array(same size as image). Plotting the numpy array not giving the original image

I separated the 3 channels of an colour image. I created a new NumPy array of the same size as the image, and stored the 3 channels of the image into 3 slices of the 3D NumPy array. After plotting the NumPy array, the plotted image is not same as original image. Why is this happening?
Both img and new_img array have same elements, but image is different.
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
img=mpimg.imread('/storage/emulated/0/1sumint/kali5.jpg')
new_img=np.empty(img.shape)
new_img[:,:,0]=img[:,:,0]
new_img[:,:,1]=img[:,:,1]
new_img[:,:,2]=img[:,:,2]
plt.imshow(new_img)
plt.show()
Expect the same image as original image.
The problem is that your new image will be created with the default data type of float64 on this line:
new_img=np.empty(img.shape)
unless you specify a different dtype.
You can either (best) copy the original image's dtype like this:
new_img = np.empty(im.shape, dtype=img.dtype)
or use something like this:
new_img = np.zeros_like(im)
or (worst) specify one you happen to know matches your data, like this,
new_img = np.empty(im.shape, dtype=np.uint8)
I presume you have some reason for copying one channel at a time, but if not, you can avoid all the foregoing issues and just do:
new_img = np.copy(img)

trying to reshape a numpy array to from 4X4 to 2X2

I have a simple numpy array of ('left_lines =', (4, 4)) which is [x1,y1,x2,y2] which is 4x4 and trying to reshape it to 2x2 and take the mean for X's and Y's . I use this code:
mean_left = np.mean(left_lines.reshape(2,2),axis=0)
But I get this error:
total size of new array must be unchanged
print(type(left_lines))
Gives:
<type 'numpy.ndarray'>
Not sure what is wrong with reshape syntax !?