I have a directory containing 4 folder (1,2,3,4). Each folder has jpg images in them. I used the code below to read the images. The problem is all images are in different shapes. So, now I have a list of images each with different shape.
1) Is there a better way to read img files from a directory? (maybe assign directly to a numpy array)
2) How can I resize the images so that they all have the same shape?
Thanks!
import imageio
import os.path
images = []
for folder in os.listdir('images'):
for filename in os.listdir('images/'+folder):
if filename.endswith(".jpg"):
img = imageio.imread('images/'+folder+'/'+filename)
img.reshape((1,img.flatten().shape[0])).shape
images.append(img)
Related
I have a folder containing images of gestures. But to make it work on my code I need to change it to X.npy and Y.npy. I looked for many questions regarding this kinda problems but still in the dark. How do I evaluate this? How do I convert the folder to create npy dataset of my own? Is there any code for this or any converter?
I found a piece of code for this purpose on github.
from PIL import Image
import os, sys
import cv2
import numpy as np
'''
Converts all images in a directory to '.npy' format.
Use np.save and np.load to save and load the images.
Use it for training your neural networks in ML/DL projects.
'''
# Path to image directory
path = "/path/to/image/directory/"
dirs = os.listdir( path )
dirs.sort()
x_train=[]
def load_dataset():
# Append images to a list
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item).convert("RGB")
im = np.array(im)
x_train.append(im)
if __name__ == "__main__":
load_dataset()
# Convert and save the list of images in '.npy' format
imgset=np.array(x_train)
np.save("imgds.npy",imgset)
You can refer to the code snippet in the following GitHub repo, that I found in google to convert a folder of images to a npy file:
https://gist.github.com/anilsathyan7/ffb35601483ac46bd72790fde55f5c04
Here in this case entire images in the folder are converted into NumPy array and are appended in a list named x_train.To convert and save this list of images in a single '.npy' format file, we can use the same code snippet:
imgset=np.array(x_train)
np.save("imgds.npy",imgset)
To convert and save this list of images in multiple '.npy' format files, use below code snippet :
imgset=np.array(x_train,dtype=object)
for i in range(len(imgset)):
np.save("imgds"+str(i)+".npy",imgset[i])
seed = 42
np.random.seed = seed
Img_Width=128
Img_Height=128
Img_Channel = 3
Train_Path = 'stage1_train/'
Test_Path = 'stage1_test/'
train_ids = next(os.walk(Train_Path))[1]
test_ids = next(os.walk(Test_Path))[1]
print(train_ids)
X_train = np.zeros((len(train_ids), Img_Height, Img_Width, Img_Channel),dtype=np.uint8)
Y_train = np.zeros((len(train_ids),Img_Height, Img_Width, 1), dtype=bool)
Above's code give as sample. I see this code and try to load my dataset.
I want to load all the image data from one folder. But it has 2 types file. 1 is .jpg file 2 is .png file. Now I want to load them into two different variables.variable = train_ids, where I can load images from several folder. But, in my dataset all the images in the same folder. How can I load them all?
This is my path, where all the images located:
F:\segmentation\ISBI2016_ISIC_Part3B_Training_Data\ISBI2016_ISIC_Part3B_Training_Data_1
[Here .jpg & .png file present]
My python code has situated on segmentation folder.
Whether the image is a JPG or a PNG makes no difference to ImageIO; it will load either format into a ndarray using the same syntax.
Regarding your the desire to load all images in a folder, we have an official example on how to read all images from a folder:
import imageio.v3 as iio
from pathlib import Path
images = list()
for file in Path("path/to/folder").iterdir():
if not file.is_file():
continue
images.append(iio.imread(file))
If you instead want to read a list of images from several folders, this works in almost the same way
import imageio.v3 as iio
list_of_files = [] # list of paths to images in various formats
images = [iio.imread(file_path) for file_path in list_of_files]
I am trying to crop high-resolution images to something more manageable. I am trying to read in a directory rather than individual images and save the new cropped images in another directory. I would like to make all the output images as .png as I have in my code.
import cv2
path = './imgs2/P5.png'
img= cv2.imread (path)
imgcropped = img [1:400, 1:400]
cv2.imwrite ('./imgs/P5-cropped', imgcropped)
Any help with this problem is appreciated.
Here's what I use in this case:
import os
import cv2
path = 'path/to/image/dir/'
dest_path = 'path/to/destination/'
for f in os.listdir(path):
image = cv2.imread(os.path.join(path, f))
imgcropped = image[1:400, 1:400]
cv2.imwrite(os.path.join(dest_path, f), imgcropped)
Assuming that:
the images in path are already .png
path contains only the images you want to convert
os.listdir will give you the names of the files inside your origin dir (including extension), which you can use in imwrite to save the image in your destination dir with the same filename.
I have Data in DICOM images, and I want to convert dicom images into png or jpg format. However, I need to convert the images in multiple folders at once using a for-loop. Here what I've done so far:
import pydicom as dicom
import cv2
# specify your image path
image_path = 'Data/LungSegmentation/NSCLC-Radiomics/LUNG1-001/09-18-2008-StudyID-69331/0.000000-82046/1-001.dcm'
ds = dicom.dcmread(image_path)
pixel_array_numpy = ds.pixel_array
image_format = '.jpg' # or '.png'
image_path = image_path.replace('.dcm', image_format)
cv2.imwrite(image_path, pixel_array_numpy)
#show image.....
plt.imshow(ds.pixel_array,cmap ='gray',vmin=0,vmax=255)
Iterate over files and folders with python modules like glob.
Just a little example:
import glob
folders = glob.glob("PATH_CONTAINING_YOUR_FOLDERS")
for folder in folders:
files = glob.glob(folder+'\*.dcm') # pick only dicom files
for file in files:
DO_YOUR_STUFF_HERE(file)
I've build a package to convert dicom files to jpg/png/bmp, you just pip install dicom2jpg then use
import dicom2jpg
dicom_dir = "/Users/user/Desktop/dir_a"
export_location = "/Users/user/Desktop/dir_b"
# convert all DICOM files in dicom_dir folder to jpg format
dicom2jpg.dicom2jpg(dicom_dir, export_location)
# convert all DICOM files in dicom_dir folder to png format
dicom2jpg.dicom2png(dicom_dir, export_location)
hope it would help
I have a data set of images in an image processing project. I want to input an image and scan through the data set to recognize the given image. What module/ library/ approach( eg: ML) should I use to identify my image in my python- opencv code?
To find exactly the same image, you don't need any kind of ML. The image is just an array of pixels, so you can check if the array of the input image equals that of an image in your dataset.
import glob
import cv2
import numpy as np
# Read in source image (the one you want to match to others in the dataset)
source = cv2.imread('test.jpg')
# Make a list of all the images in the dataset (I assume they are images in a directory)
filelist = glob.glob(r'C:\Users\...\Images\*.JPG')
# Loop through the images, read them in and check if an image is equal to your source
for file in filelist:
img = cv2.imread(file)
if np.array_equal(source, img):
print("%s is the same image as source" %(file))
break