I have a loop, where I read images and resize them to 32x32x3
for i, filename in enumerate(os.listdir(path)):
img = plt.imread(path+filename)
out = imresize(img, [32,32])
I tried to store it in a list and convert it to an numpy array
for i, filename in enumerate(os.listdir(path)):
img = plt.imread(path+filename)
out = imresize(img, [32,32])
inet_signs.append(out)
a = np.array(inet_signs)
But this only resulted in the error:
ValueError: could not broadcast input array from shape (32,32,3) into
shape (32,32)
Related
How can I add these images which I have converted to a (95,95) array into an array that gives me the number of images I have (in my case 10) and the dimensions of those images (95,95)?
My desired output would be an array <10,95,95>.
This is my code so far, thank you! code:
import cv2
import os
from matplotlib import pyplot as plt
# https://www.ocr2edit.com/convert-to-txt
x_train = "C:/Users/cuevas26/ae/crater_images_test"
categories = ["crater"]
#for category in categories:
path = x_train
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
imgs = cv2.resize(img_array, (95, 95))
plt.imshow(imgs, cmap="gray")
plt.show()
print(type(imgs))
print(imgs.shape)
We may append the images to a list, and convert the final list into NumPy array using numpy.stack.
Start with an empty list:
images_list = []
In the loop, after img = cv2.resize, append the resized image to the list:
images_list.append(img)
After the end of the loop, convert the list into 3D NumPy array:
images = np.stack(images_list, axis=0)
images.shape is (10, 95, 95).
images.shape[0] is the number of images.
images.shape[1:] is the image dimensions (95, 95).
Use images[i] for accessing the image in index i.
Code sample:
import cv2
import os
from matplotlib import pyplot as plt
import numpy as np
# https://www.ocr2edit.com/convert-to-txt
x_train = "C:/Users/cuevas26/ae/crater_images_test"
images_list = [] # List of images - start with an empty list
# For category in categories:
path = x_train
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img_array, (95, 95))
images_list.append(img) # Append the new image into a list
# Convert the list to of 2D arrays into 3D NumPy array (the first index is the index of the image).
# https://stackoverflow.com/questions/27516849/how-to-convert-list-of-numpy-arrays-into-single-numpy-array
images = np.stack(images_list, axis=0)
print(type(images)) # <class 'numpy.ndarray'>
print(images.shape) # (10, 95, 95)
n_images = images.shape[0]
# Show the images (using cv2.imshow instead of matplotlib)
for i in range(n_images):
cv2.imshow('img', images[i])
cv2.waitKey(1000) # Wait 1 second
cv2.destroyAllWindows()
I have an array (generated from PIL image) of shape (500,500,3) and need to convert it to (180,180,3). No matter what I try, it doesn't seem to work. Here is the code:
window = img[i:i+window_size_dim1, j:j+window_size_dim2]
img = Image.fromarray(window)
img_array = image.img_to_array(img)
img_array.reshape((180,180,3))
and the error:
ValueError: cannot reshape array of size 750000 into shape (180,180,3)
any ideas are much appreciated!
mypath='/Users/sachal/Desktop/data_raw/normal_1/images'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = np.asarray(np.empty(len(onlyfiles), dtype=object))
for n in range(0, len(onlyfiles)):
images[n] = cv2.imread( join(mypath,onlyfiles[n]) )
#--------------------------------------------------------------------------------
resized = np.asarray(np.empty(len(onlyfiles), dtype=object))
img_f = np.asarray(np.empty(len(onlyfiles), dtype=object))
for n in range(0, len(onlyfiles)):
resized[n] = cv2.resize(images[n],(101,101))
img_f[n] = cv2.cvtColor(resized[n], cv2.COLOR_BGR2YUV)
train_img = np.asarray(img_f)
#--------------------------------------------------------------------------------
In the above code first I am loading images using opencv then I am resizing and changing their colour space in the second block.
My batch size is 6408 and dimensions of images are 101*101*3
When i do train_img.shape i get(6408,) and upon train_img[i].shape i get 101*101*3 and I am unable to train my neural network model because of this and the dimensions i want are 6408*101*101*3
I tried reshaping with this train_img.resize(6408,101,101,3) i got this ValueError: cannot resize an array that references or is referenced
by another array in this way. Use the resize function
and while fitting my model with i got this error Error when checking input: expected conv2d_3_input to have 4 dimensions, but got array with shape (6408, 1)
I want to know if i can change the dimensions of my input with the current method i am using to load my images.
You shouldn't use the dtype=object here. OpenCV creates ndarray images anyway.
Here is a corrected version of your code:
mypath='/Users/sachal/Desktop/data_raw/normal_1/images'
onlyfiles = [ f for f in os.listdir(mypath) if os.path.isfile(join(mypath,f)) ]
images = []
for file in onlyfiles:
img = cv2.imread(os.path.join(mypath,file))
resized_img = cv2.resize(img, (101, 101))
yuv_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2YUV)
images.append(yuv_img.reshape(1, 101, 101, 3))
train_img = np.concatenate(images, axis=0)
print(train_img.shape)
In the loop, you load each image, resize it, convert it to YUV then put it in a list. At the end of the loop, your list contains all your training images. You can pass it to np.concatenate to create an ndarray.
I have a requirement to read image files( 28*28) from a folder and stack them together to make a single array for analysis.
I have the following code:
for fname in os.listdir(dirname):
im = Image.open(os.path.join(dirname, fname))
imarray = np.array(im)
final = np.stack((final,imarray ), axis = 0)
am getting the following error:
ValueError: all input arrays must have the same shape
imarray is (28,28) and i have 60K images in that folder so i want to make a array of size (60000,28,28)
Thanks for the help
NK
Build a list of all components and stack them once:
alist = []
for fname in os.listdir(dirname):
im = Image.open(os.path.join(dirname, fname))
imarray = np.array(im)
alist.append(imarray)
final = np.stack(alist) # axis=0 is the default
This will join them on a new initial axis.
I am trying to customize an existing code to suit my own need. Originally, the code use imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8) to store a list of image files in an numpy array format. Iterating the folder, each image file is read as follows img = skimage.io.imread(os.path.join(train_data_path, image_name)) It works just fine.
The code is as follows:
image_rows = 420
image_cols = 580
imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
i=0
for image_name in images:
img = skimage.io.imread(os.path.join(train_data_path, image_name))
img = np.array([img])
imgs[i]=img
i+=1
In order to suit my own need, I tend to have image file array with the shape [total, image_rows,image_cols,1]. In other words, I modified it as imgs = np.ndarray((total,image_rows, image_cols,1), dtype=np.uint8) However, running the code causes the following error
imgs[i] = img
ValueError: could not broadcast input array from shape (1,420,580) into shape
(420,580,1)
Are there any way to change the shape of img, which originally has shape of [1,420,580] after reading from file. How can I change it to [420,580,1] without affecting the corresponding pixel values in the image.
You want to transpose the dimensions. It can be done using the transpose method:
img = img.transpose(1,2,0)
(for your case)