images to np array and keep the order - python

I am trying to take 1967 jpg images to a np array with following codes. How do I keep the original order of the images in the array?
import cv2
import glob
import numpy as np
X_data = []
files = glob.glob ("/content/drive/My Drive/CourseWork/images/emotionet_validation/*.jpg")
for myFile in files:
print(myFile)
image = cv2.imread (myFile)
X_data.append (image)
print('X_data shape:', np.array(X_data).shape)

https://docs.python.org/3/howto/sorting.html
import cv2
import glob
import numpy as np
X_data = []
files = glob.glob ("/content/drive/My Drive/CourseWork/images/emotionet_validation/*.jpg")
sorted(files)
## Do you need sort to ignore case?
## sorted(files, key=str.casefold)
for myFile in files:
print(myFile)
image = cv2.imread (myFile)
X_data.append (image)
print('X_data shape:', np.array(X_data).shape)

Related

Apply bitwise operation two different folders in python

I'm trying to combine all images one by one from two different folders, for example, I have those two folders
-folder1
-+img1.jpg
-+img2.jpg
-+img3.jpg
...
-folder2
-+img_1.jpg
-+img_2.jpg
-+img_3.jpg
what I would like to do is apply bitwise operation to img1.jpg and img_1.jpg, img2.jpg and img_2.jpg ...
I'm trying with this code in google colab but no any output
Code is as follows:
import os
import cv2
import pathlib
from google.colab.patches import cv2_imshow
folder1=pathlib.Path("/content/drive/MyDrive/Healthy")
folder2=pathlib.Path("/content/drive/MyDrive/mask_Healthy")
for filename in os.listdir(folder1):
for filename2 in os.listdir(folder2):
if (filename == filename2):
img1 = cv2.imread(os.path.join(folder1,filename),cv2.IMREAD_UNCHANGED)
img1 = cv2.resize(img1,(224, 224))
img2 = cv2.imread(os.path.join(folder2,filename2),cv2.IMREAD_UNCHANGED)
img2 = cv2.resize(img2,(224, 224))
dest_and = cv2.bitwise_and(img2,img1,mask = None)
cv2_imshow(dest_and)
make_dir(os.path.join("segmented", "seg", cv2.imwrite('filename.jpg',dest_and )))

how to convert a nift folder to png images?

*library
there is a mostly known library imported from NumPy and imageio
import NumPy as np
import os
import nibabel as nib
import imageio
// method where I have I write code to convert a nift to png
Method
convert a nift(.nii) image to png image
def nii_to_image(niifile):
filenames = os.listdir(filepath) #read nii folder
slice_trans = []
#filename is the path of nii image
for f in filenames:
#Start reading nii files
img_path = os.path.join(filepath, f)
img = nib.load(img_path) #read nii
img_fdata = img.get_fdata()
fname = f.replace('.nii','')
# Remove the nickname of nii
img_f_path = os.path.join(imgfile, fname)
#Create a folder corresponding to the image of nii
if not os.path.exists(img_f_path):
os.mkdir(img_f_path) #New folder
# to image
(x,y,z) = img.shape
for i in range(z): #x is the sequence of images
silce = img_fdata[i, :, :] #Select which direction the slice can be
imageio.imwrite(os.path.join(img_f_path,'{}.png'.format(i)), silce) #Save image
#main function where fill path was gived
main
if __name__ == '__main__':
filepath = '/content/drive/MyDrive/sem 8/dataset/pr'
imgfile = '/content/drive/MyDrive/sem 8/dataset/propi'
nii_to_image(filepath)
After you load the nifti file as NumPy array as you did, run on every slice (z from img.shape) and then save the array to png.
Make sure that when you run on each slice you save only the existing one (the z_slice_number):
slice = img_fdata[:, :, z_slice_numer]
And to save this slice you can do as follow (or another way from here):
matplotlib.image.imsave('name.png', slice)

numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching

I'm iterating through a directory to resize images and then save the newly reshaped images in another existing directory. I keep getting the following error:
Traceback (most recent call last):
File "preprocessingdatacopy.py", line 23, in <module>
new_filename = image_resized + 'new.png'
numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')
The code:
import matplotlib.pyplot as plt
import skimage
from sklearn import preprocessing
from skimage import data, color
import os
from skimage.transform import resize, rescale
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage import io
import cv2
import os
from pathlib import Path
directory_in_str = "/home/briannagopaul/imagemickey/"
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
print(file)
filename = directory_in_str + os.fsdecode(file)
if filename.endswith(".png"):
img = mpimg.imread(filename)
# cropped = img[484:384, 380:384]
image_resized = resize(img, (128, 128))
path2 = ("/home/briannagopaul/preprocessed")
new_filename = image_resized + 'new.png'
image_file.save(str(path2 / new_filename))
You cannot concatenate an image to a string. You need to replace image_resized with a string data type (i.e the file name) because skimage.transform.resize() returns an image as an N-dimensional array.

Reading Multiple tiff files in python from a folder

I have a folder containing 10K tiff files, how can i import all the files using python so that i can do some predictive modelling.
thanks
NK
Use the following approach:
import os
from PIL import Image
import numpy as np
dirname = 'tiff_folder_path'
final = []
for fname in os.listdir(dirname):
im = Image.open(os.path.join(dirname, fname))
imarray = np.array(im)
final.append(imarray)
final = np.asarray(final) # shape = (60000,28,28)

Opening an Image from a specific file?

import glob
import numpy as np
from PIL import Image
filename = glob.glob('/home/ns3/PycharmProjects/untitled1/stego.pgm')
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)
Keeps giving me this error:
im= Image.open(filename)
File "/home/ns3/.local/lib/python2.7/site-packages/PIL/Image.py", line 2416, in open
fp = io.BytesIO(fp.read())
AttributeError: 'list' object has no attribute 'read
How can I open an image from that specific path and use the image as array I?
The issue is that glob.glob() returns a list (a possibly-empty list of path names that match pathname) and you want a string.
so either insert a [0]
import glob
import numpy as np
from PIL import Image
filenames = glob.glob('/home/ns3/PycharmProjects/untitled1/stego.pgm')
filename = filenames[0]
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)
or skip glob all together
import numpy as np
from PIL import Image
filename = '/home/ns3/PycharmProjects/untitled1/stego.pgm'
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)

Categories

Resources