I want to convert a 3D image into a numpy array, making sure to preserve the fact that it is a grayscale image.
I have created an empty array in which I would like to load these images into where x,y,z, are the respective dimensions and channels = 1.
img_array = np.ndarray((len(directory), x, y, z, channels), dtype=np.uint8
This is the code I used to convert the original .mat files to an array and load each one into the empty array I just created
i=0
for array in directory:
OG = loadmat(array, appendmat = True) #load the mat file
OG = OG['new_OG'] #get the actual image from the list
OG =np.array(OG) #convert to an array
img_array[i] = OG #append to the empty array
However, when I try to append it to img_array in the last line, it doesn't work because of the following error:
ValueError: could not broadcast input array from shape (80,84,80) into shape (80,84,80,1)
So how can I make sure I turn the .mat file into a numpy array with the shape I need: (x,y,z,1)?
Related
I am trying to shuffle the pixel positions in image to get encrypted(distorted) image and decrypt the image using the original position in python. This is what i got from GPT and the shuffled images appear to be black.
from PIL import Image
import numpy as np
# Load the image
img = Image.open('test.png')
# Convert the image to a NumPy array
img_array = np.array(img)
# Flatten the array
flat_array = img_array.flatten()
# Create an index array that records the original pixel positions
index_array = np.arange(flat_array.shape[0])
# Shuffle the 1D arrays using the same random permutation
shuffled_index_array = np.random.permutation(index_array)
shuffled_array = flat_array[shuffled_index_array]
# Reshape the shuffled 1D array to the original image shape
shuffled_img_array = shuffled_array.reshape(img_array.shape)
# Convert the NumPy array to PIL image
shuffled_img = Image.fromarray(shuffled_img_array)
# Save the shuffled image
shuffled_img.save('shuffled_image.png')
# Save the shuffled index array as integers to a text file
np.savetxt('shuffled_index_array.txt', shuffled_index_array.astype(int), fmt='%d')
# Load the shuffled index array from the text file
shuffled_index_array = np.loadtxt('shuffled_index_array.txt', dtype=int)
# Rearrange the shuffled array using the shuffled index array
reshuffled_array = shuffled_array[shuffled_index_array]
# Reshape the flat array to the original image shape
reshuffled_img_array = reshuffled_array.reshape(img_array.shape)
# Convert the NumPy array to PIL image
reshuffled_img = Image.fromarray(reshuffled_img_array)
# Save the reshuffled image
reshuffled_img.save('reshuffled_image.png')
I'm trying to shuffle the pixel positions in an image but im stuck with what is wrong going on here.
You are really just missing a reversion of the permutation performed by numpy in the line np.random.permutation(index_array). That can be obtained by changing the line creating the reshuffled array to the following
# Rearrange the shuffled array using the shuffled index array
reshuffled_array = shuffled_array[np.argsort(shuffled_index_array)]
An explanation for reversion can be found here: Inverting permutations in Python
From this question How to convert Nifti file to Numpy array? , I created a 3D numpy array of nifti image. I made some modifications to this array, like I changed depth of the array by adding padding of zeroes. Now I want to convert this array back to nifti image, how can I do that?
I tried:
imga = Image.fromarray(img, 'RGB')
imga.save("modified/volume-20.nii")
but it doesn't identify nii extension. I also tried:
nib.save(img,'modified/volume-20.nii')
this is also not working, because img must be nibabel.nifti1.Nifti1Image if I want to use nib.save feature. In both of the examples above img is a 3D numpy array.
Assuming that you a numpy array and you want to use nib.save function, you need to first get the affine transformation.
Example:
# define the path to the data
func_filename = os.path.join(data_path, 'task-rest_bold.nii.gz')
# load the data
func = nib.load(func_filename)
# do computations that lead to a 3D numpy array called "output"
# bla bla bla
# output = np.array(....)
# to save this 3D (ndarry) numpy use this
ni_img = nib.Nifti1Image(output, func.affine)
nib.save(ni_img, 'output.nii.gz')
Now you will be able to overlay the output.nii.gz onto the task-rest_bold.nii.gz
I am trying to load own image dataset from a folderwith two sub directories where all the images are 16bit png in RGB scale and the dimension of the images are (64*64). I am converting them to gray scale and forced the numpy array to have data type as uint16. It is returning me a list of images as (64*64) numpy arrays.
path="D:/PROJECT ___ CU/Images for 3D/imagedatanew/Training2/"
imageset=[]
image_labels=[]
for directory in os.listdir(path):
for file in os.listdir(path+directory):
print(path+directory+"/"+file)
img=Image.open(path+directory+"/"+file)
featurevector=numpy.array(img.convert("L"),dtype='uint16')
imageset.append(featurevector)
image_labels.append(directory)
But when I am trying to convert this list of 2D arrays into a 3D array, I cant do that.
im=numpy.array(imageset)
im.shape
>>> im.shape
>>> (207,) ##there are 207 images in total
I want the the array as (207,64,64)
and also when I run the im array, it returns me dtype as "object", which I cant understand
I'm trying to open an image with size (520,696) but when I use this
array = np.array([np.array(Image.open(folder_path+folders+'/'+'images'+'/'+image))], np.int32).shape`
I'm getting the shape as
(1, 520, 696, 4)
The problem is with this shape I can't convert it to image using toimage(array); I get
'arr' does not have a suitable array shape for any mode.
Any suggestions on how may I read that image using only (520,696)?
The problem is the additional dumb dimension. You can remove it using:
arr = np.squeeze(arr)
You should load the picture as a single picture instead of loading it as a stack and then removing the irrelevant stack dimension. The basic procedure could be something like this:
from PIL import Image
pic = Image.open("test.jpg")
pic.show() #yup, that's the picture
arr = np.array(pic) #convert it to a numpy array
print(arr.shape, arr.dtype) #dimension and data type
arr //= 2 #now manipulate this array
new_pic = Image.fromarray(arr) #and keep it for later
new_pic.save("newpic.bmp") #maybe in a different format
I am reading thousands of images (all three channels), one by one, in form of a numpy ndarray and append them to a list. At the end I want to convert this list into a numpy array:
import numpy as np
from PIL import Image
def read_image_path(path, img_size=227):
img = Image.open(path)
img = np.array(img.resize([img_size, img_size]))
return img
I read each image path from a dictionary that looks like:
{1:{'img_path': 'path-to-image', 'someOtherKeys':'...'}, 2:{...}}
images = []
for key in key:
img = read_image_path(dataset_dictionary[key]['img_path'])
images.append(img)
Up to here it's all fine. I have a list of ndarray image matrices of size (227,227,3). But when I try to convert "images" to numpy array and return it from the function, it gives the following error:
return np.array(images)
return np.array(images)
ValueError: could not broadcast input array from shape (227,227,3) into shape (227,227)
I will be grateful to have anyone's idea about this.
Most likely you have a img (or images) which has the shape of (227,227) instead of (227,227,3).
The following code should tell you which image is the offender.
for key in key:
img = read_image_path(dataset_dictionary[key]['img_path'])
if img.shape != (227,227,3):
print(key)