Reading images from directory in python - python-3.x

I am facing the problem in reading images from multiple directory in python. Like there is single image in png format and it is located in multiple folders. I want to keep a for loop on that and then access the image like from every folder. So what could be the way to read those images from the particular folder?
import os
from os import listdir
from os.path import isfile, join
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import glob
%matplotlib inline
mypath='E:/Datasets/CBIS-DDSM PNG/Converted_Test'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = np.empty(len(onlyfiles), dtype=object)
for n in range(0, len(onlyfiles)):
images[n] = cv2.imread( join(mypath,onlyfiles[n]) )

Maybe you should try another method to reach to the directories for reading images.
in imread() you can pass the directory .so you can use str() and + to combine dynamic directories and fixed directory.
Here is the example maybe help you :
path = '/home/pictures/1'
for i in range(2) :
image = cv2.imread(str(path)+'1'+'/222.jpg')
plt.imshow(image)
plt.show()
In this example I had 2 folder 11 and 12 so with a for loop I changed folders that I need.

Related

OSError: Unable to open file (file signature not found)

I am currently doing an assignment on deep learning by downloading the assignment files from github.
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
%matplotlib inline
You are given a dataset ("data.h5") containing: - a training set of m_train images labeled as cat (y=1) or non-cat (y=0) - a test set of m_test images labeled as cat or non-cat - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px).
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
I ran the setup.sh file too but the error doesn't seem to go away.
lr_utils.py file:
import numpy as np
import h5py
def load_dataset():
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
classes = np.array(test_dataset["list_classes"][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
Kindly help!
I solved the issue by downloading uncorrupted .h5 files and putting them in the folder datasets/ in the same directory.
The files you downloaded are corrupted. You can visit https://github.com/abdur75648/Deep-Learning-Specialization-Coursera to download the uncorrupted files.
you can download uncorrupted files from here :
https://www.kaggle.com/datasets/muhammeddalkran/catvnoncat
and replace it in the directory of the corrupted files

`FileNotFoundError: No such file: '/content/Weeds_Detectiontrain/1.png'` How to write the correct directory

I'm new to python! I am trying to upgrade myself. However, I have a dataset namely tree_dataset which contains 3 folders i.e. test, train, and validation. Each folder contains 9 different folders (classes). Now, I want to show a sample of all first images (data) from the 9 different classes.
My code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(style="whitegrid")
import os
import imageio
import skimage
import skimage.io
import skimage.transform
# Showing sample of all first images (data) from the 09 different classes
f, ax = plt.subplots(nrows=1,ncols=9, figsize=(20, 10))
i=0
for d in directory:
file='/content/tree_dataset'+d+'/1.png'
im=imageio.imread(file)
ax[i].imshow(im,resample=True)
ax[i].set_title(d, fontsize=8)
i+=1
Error: FileNotFoundError: No such file: '/content/Weeds_Detectiontrain/1.png'

Assigning a filepath to a variable in Python 3

I am trying to convert few camera-clicked images of handwritten Gujarati characters to the form of MNIST dataset as I intend to pass the Gujarati handwritten characters images to the MNIST deep learning model. And as part of that, I'm trying to assign a file path to a variable named "datadir". But when executing the below code in Ubuntu 16.04, the terminal throws the error which looks like this:
File "gujaratinn.py", line 7
datadir = /home/cryptoaniket256/Desktop/opencv-3.4.1/project/Resize
^
SyntaxError: invalid syntax
Note that the name of the file is gujaratinn.py and all the camera-clicked images are stored in the Resize folder.
import numpy as np
import matplotlib.pyplot as py
import os
import cv2
from pathlib import Path
datadir = Path("/home/cryptoaniket256/Desktop/opencv-
3.4.1/project/Resize")
fileToOpen = datadir/"practice.txt"
f = open(fileToOpen)
print(f.read())
Are you affecting datadir with a path you wrote on 2 rows in your code ?
Try to put line 7 and 8 on the same row or change the quotes like that:
import numpy as np
import matplotlib.pyplot as py
import os
import cv2
from pathlib import Path
datadir = Path("""/home/cryptoaniket256/Desktop/opencv-3.4.1/project/Resize""")
fileToOpen = datadir/"practice.txt"
f = open(fileToOpen)
print(f.read())

import data from multiple file and summing column wise

I have n number of txt files each having 99 floating numbers in 99 column. I read each files and append all data by following script.
import glob
import numpy as np
import matplotlib.pyplot as plt
msd_files = (glob.glob('MSD_no_fs*'))
msd_all=[]
for msd_file in msd_files:
# print(msd_file)
msd = numpy.loadtxt(fname=msd_file, delimiter=',')
msd_all.append(msd)
After that I need to make column wise summation of each files. for example file1,column1+file2,column1+...+file(n)column(1) and iterate this for all column. What will be the effective way to perform this? Can I use list comprehension for that?
**edited code and it works fine now.
import glob
import numpy as np
import matplotlib.pyplot as plt
msd_files = (glob.glob('MSD_no_fs*'))
msd_all=[]
for msd_file in msd_files:
with open(msd_file) as f:
for line in f:
# msd_all.append([float(v) for v in line.strip().split(',')])
msd_all.append(float(line.strip()))
msa_array = np.array(msd_all)
x=np.split(msa_array,99)
x=np.array(x)
result=np.mean(x,axis=0)
print(result.shape)
print(len(result))
It depends on efficiency level you want. Using numpy to load many csv files might be a bad choice. Here is my suggestion.
import glob
import numpy as np
msd_files = (glob.glob('MSD_no_fs*'))
msd_all=[]
for msd_file in msd_files:
with open(msd_file) as f:
for line in f:
msd_all.append([float(v) for v in line.strip().split(',')])
msa_array = np.array(msd_all)
result = msa_array.sum(axis=0)

How to address to folders that differ only in one letter in python?

i have 3 folders with names :
s1 , s2 , s3
and each folder consist 2 ".png " files with names :
1.png , 2.png
i'm using this code to read those images but it ain't working:
import numpy as np
import imageio as img
import matplotlib.pyplot as plt
im = [[]]*6
for i in range(3):
for j in range(2):
im[i*2+j] = img.imread('C:/Users/Kinter4/Desktop/face/"s{}".format(i)/"
{}.png".format(j)')
it doesn't recognize "s{}".format(i) as a command in other hand it recognizes it as part of address.
any solution for that?
thanks
"C:/Users/Kinter4/Desktop/face/s{}/{}.png".format(i, j)

Resources