glob.glob doesn't find any images - python

I'm trying to get all images from a directory to a list with glob.glob with the following code:
# I'm loading the path from a json file with:
CONFIG_FILE = "Config_path"
IMAGE_DIR = "image_dir"
try:
with open(CONFIG_FILE) as json_file:
params = json.load(json_file)
json_file.close()
except FileNotFoundError:
print(f"Error")
image_dir = params[IMAGE_DIR]
images_dir = image_dir + "*.jpg"
images = glob.glob(images_dir)
for fname in images:
img = cv2.imread(fname)
...
My path in the json file looks like: "C://path/path/some_more_path/". My only idea is that there is some problem with my path. But there is no symbol used that could cause any problem. In my understanding.

Related

How to create and download a zip file with a list of images?

Here I have list of images with their url.
I want to create a zip and store all the images inside zip. After extract the zip file I want the images inside folder.
What's happening with the below code is:
it creates zip and downloads but when I extract the zip file, there are so many folders
like zipfoldername/home/user/my_project/img and only inside img folder there are files.
I want is only zipfoldername/img.
Also inside img folder files doesn't have images it has image_url only. I want to store image from that image url in the extracted file.
image_list = ['https://example.com/media/file1.jpg', 'https://example.com/media/file2.jpg']
folder = os.path.join(settings.BASE_DIR, "imgs")
if not os.path.exists(folder):
os.mkdir(folder)
for i, imgfile in enumerate(image_list):
with open(os.path.join(folder, str(i)), 'wb+') as f:
f.write(imgfile)
response = HttpResponse(content_type='application/zip')
s = StringIO.StringIO()
zip_file = zipfile.ZipFile(s, "w")
folder_files = os.listdir(folder)
for filename in folder_files:
file = os.path.join(folder, filename)
zip_file.write(file)
zip_file.close()
resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed")
resp['Content-Disposition'] = 'attachment; filename=gik.zip'
return resp
Using os to get the filename and using writestr to write the bytes of the downloaded file to the zipfile
import os
import zipfile
import requests
images = [
"https://via.placeholder.com/350x150.jpg",
"https://via.placeholder.com/350x250.jpg",
]
with zipfile.ZipFile('someZipFile.zip', 'w') as img_zip:
for image_url in images:
img_name = os.path.basename(image_url)
img_data = requests.get(image_url).content
img_zip.writestr(img_name, img_data)
And if you want a folder called img inside the zip folder you could change:
img_zip.writestr(img_name, img_data)
to
img_zip.writestr(f"img/{img_name}", img_data)
If your returning the archive in a HTTP response you can save it to a buffer and then respond with the buffer
buffer = io.BytesIO()
with zipfile.ZipFile(buffer , 'w') as img_zip:
...
response = HttpResponse(buffer.getvalue())
response['Content-Type'] = 'application/x-zip-compressed'
response['Content-Disposition'] = 'attachment; filename=file.zip'
return response

Converting directory with images to csv file in python

Im trying to copy the pixel information of a group of images to a CSV, however when I try the following code, Im unable to create the csv. Is there any other way to copy the pixels to a csv?
from PIL import Image
import numpy as np
import sys
import os
import csv
# default format can be changed as needed
def createFileList(myDir, format='.png'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
for name in files:
if name.endswith(format):
fullName = os.path.join(root, name)
fileList.append(fullName)
return fileList
# load the original image
myFileList = createFileList('/test/surprise')
for file in myFileList:
print(file)
img_file = Image.open(file)
# img_file.show()
# get original image parameters...
width, height = img_file.size
format = img_file.format
mode = img_file.mode
# Make image Greyscale
img_grey = img_file.convert('L')
#img_grey.save('result.png')
#img_grey.show()
# Save Greyscale values
value = np.asarray(img_grey.getdata(), dtype=np.int).reshape((img_grey.size[1], img_grey.size[0]))
value = value.flatten()
print(value)
with open("imagenes.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(value)
I would like to generate a csv with the pixel information similar to FER2013.csv as can be see in the following image.

Display FileName of a Image Python imshow

Please,
I'm trying to display the filename of a jpeg but i could not find how to.
I want to display the image + the filename of the image.
img_dir = "paintings/"
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
img = imageio.imread(f1)
data.append(img)
plt.imshow(data[40])
Thanks
You can try plt.title(filename):

How can I recognize "PNG (Portable Network Graphics)" files in numpy.ndarray?

I need to find png files in numpy.ndarray. It is even possible?
list_of_files contains files with the extension ['jpg', 'jpeg', 'bmp', 'tif', 'tiff', 'png'].
for f in list_of_files:
stream = open(f, 'rb')
bytes = bytearray(stream.read())
numpy_array = numpy.asarray(bytes, dtype=numpy.uint8)
image = cv2.imdecode(numpy_array, cv2.IMREAD_UNCHANGED)
Since you want to process just the png files, how about loading just those? You can use the glob library for this:
import glob
my_path = "<path_to_folder>"
for f in glob.glob(my_path + "/*.png"):
#Do whatever here
Essentially, glob.glob(my_path + "/*.png") gives you a list of the files in your path who have the desired extension.
You could identify the .png file before reading the image:
images={'png':[],'others':[]}
for f in list_of_files:
if f.split('.')[1:] == 'png':
with open(f, 'rb') as stream:
bytes = bytearray(stream.read())
img_array = numpy.asarray(bytes, dtype=numpy.uint8)
images['png'].append(cv2.imdecode(img_array, cv2.IMREAD_UNCHANGED))
else:
# w/e you want to do with the other images
You could use imghdr.what.
import imghdr
for f in list_of_files:
if (imghdr.what(f) == "png"):
print(f + " is a PNG file")

Copy images from folders

I have a bunch of jpgs in one folder (images) that I want to copy across to another folder (destination_folder). When they are copied across, I want the jpg files to be renamed as follows: filename1_red.jpg, filename2_red.jpg (i.e. adding on the suffix _red at the end)
I have the following so far:
import os
images = os.listdir('C:/Users/Admin-dsc/Documents/.../buses and motorcycles')
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
for img in images:
filename = os.path.basename(img)
copyfile(img, os.path.join(destination_folder, filename))
Question 1: I get this error that I don't understand - how do I resolve it:
FileNotFoundError: [Errno 2] No such file or directory: 'RWG074059_2_o.jpg'
Question 2: I am unsure how to get the suffix.
Can anyone help?
os.listdir returns just the file names of the files in the specified folder, it doesn't return the complete path to the file. So, you need to join the source folder path with img:
import os
from shutil import copyfile
source_folder = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
images = os.listdir(source_folder)
for img in images:
filename, ext = os.path.splitext(img)
filename = filename + '_red' + ext
copyfile(os.path.join(source_folder, img), os.path.join(destination_folder, filename))
How to debug this error:
import os
directory = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
images = os.listdir(directory)
for img in images:
print(img)
filename = os.path.basename(img)
print(filename)
Output:
main.py
main.py
What you can see:
You see that listdir() only returns filenames. You need to prepend the source folder again.
How to fix:
import os
directory = './'
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
images = os.listdir(directory)
for img in images:
print(img)
filename = os.path.basename(img)
print(filename)
# prepend path again
source = os.path.join(directory,img)
target = os.path.join(destination_folder,img)
print(source, "=>", target)
# copyfile(source, target)
Output:
./main.py => C:/Users/Admin-dsc/Documents/.../Buses/main.py
img only contains the name of the image, not the complete path information.
Build an aboslute path instead when you specify the source image:
import os
source_folder = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
images = os.listdir(source_folder)
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
for img in images:
filename = os.path.basename(img)
copyfile(os.path.join(source_folder, img), os.path.join(destination_folder, filename))

Categories

Resources