I have a folder with numerous images(about 300), I am gonna save the python file which will be splitting the images into red, green and blue channels and saving them as _red, _green, _blue, preceded by the original image name itself in a different folder. For example if the image is named "image 001", then the images obtained after the split are: "image 001_red", "image 001_green", "image 001_blue". Now, is there a way I can obtain the images one after the other using the OS library? (Appreciate any answer what-so-ever, because this is my first question on this site)
You are asking how to read an image list from a directory to python. Here is how.
from os import walk
# Get file list
def getImageList(path):
for (dirpath, dirnames, filenames) in walk(path):
return filenames
# Demo printing file names
filelist = getImageList("path/to/image/dir")
for fileName in fileList:
print(fileName)
getImageList(path) function returns all files (not directories) in a given path. Place all your images inside a directory, and use the function to get the file list.
Hope this helped.
Related
I have Folder Named A, which includes some Sub-Folders starting name with Alphabet A.
In these Sub-Folders different images are placed (some of the image formats are .png, jpeg, .giff and .webp, having different names
like item1.png, item1.jpeg, item2.png, item3.png etc). From these Sub-Folders I want to get list of path of those images which endswith 1.
Along with that I want to only get 1 image file format like for example only for jpeg. In some Sub-Folders images name endswith 1.png, 1.jpeg, 1.giff and etc.
I only want one image from every Sub-Folder which endswith 1.(any image format). I am sharing the code which returns image path of items (ending with 1) for all images format.
CODE:
here is the code that can solve your problem.
import os
img_paths = []
for top,dirs, files in os.walk("your_path_goes_here"):
for pics in files:
if os.path.splitext(pics)[0] == '1':
img_paths.append(os.path.join(top,pics))
break
img_paths will have the list that you need
it will have the first image from the subfolder with the name of 1 which can be any format.
Incase if you want with specific formats,
import os
img_paths = []
for top,dirs, files in os.walk("your_path_goes_here"):
for pics in files:
if os.path.splitext(pics)[0] == '1' and os.path.splitext(pics)[1][1:] in ['png','jpg','tif']:
img_paths.append(os.path.join(top,pics))
break
Thanks, to S3DEV for making it more optimized
I want to sort many face images to make good face images data. So, I want there's no blur, no multiple faces in one image in my images data.
I've tried the code, but my code just can check single image at once
image = face_recognition.load_image_file("./pictures/image.jpg")
face_locations = face_recognition.face_locations(image)
print(face_locations)
Is there any code to make my code can detect multiple images at once? I'd appreciate any answer. Thanks in advance!
There are no API calls in face_recognition, that allows loading several images in on time.
This page with the API documentation at readthedocs.
So I think you have to load the list of the images from a directory and then use it in a loop to get images objects.
This is This is great SO thread with answer how to load the list of files from directory using Python: Find all files in a directory with extension .txt in Python
I have no idea which framework or library you are using and you are not specific either.
As tags suggest I will do it in pythonic way.
Walk over the current directory and find and filter files by extension.
import os
def getfiles():
for root, dirs, files in os.walk("."):
for name in files:
yield os.path.join(root, name)
files = filter(lambda image: (image[-3:] == '.jpg' or image[-3:] == '.png'), getfiles())
# now you can loop your image detection api call.
for file in files
image = face_recognition.load_image_file(file)
face_locations = face_recognition.face_locations(image)
print(face_locations)
I need to read a folder with a lot of .bmp files, and put all of the images on a lits of images. I do not know how to handle the adress. I was doing some thing like this:
adress = "c:/Users/My Name/Desktop/assignment/*.bmp"
imageArray = [cv2.imread(file) for file in glob.glob(adress)]
numImg = len(imageArray)
Inside the assignment folder, there is the Images folder with all the images I need. How to make this work?
Change working directory first:
If you change to the directory of interest first, it may be easier.
import glob, os
os.chdir("/mydir")
image_type = "*.bmp"
imageArray = [cv2.imread(file) for file in glob.glob(image_type)]
numImg = len(imageArray)
This LINK has some nice info about reading files in directories
How can I make directory & put image in the directory?
I wrote the following code in data.py:
import os
import cv2
import argparse
import numpy as np
import math
parser = argparse.ArgumentParser(description='')
parser.add_argument('input_dir' ,help='input directory')
parser.add_argument('output_dir' ,help='out directory')
args = parser.parse_args()
def find_all_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
p=os.path.join(root, file)
p=p.split("/")[len(p.split("/"))-2]
name, ext = os.path.splitext(p)
yield os.path.join(root, file)
dirname=args.output_dir
if not os.path.exists(dirname):
os.mkdir(dirname)
folder_img = find_all_files(args.input_dir)
im =cv2.imread(folder_img)
cv2.imwrite(args.output_dir ,im)
Now when I run command python data.py ./photo ./copy_photo, find a writer for the specified extension in function imwrite error happens. I want to make a directory copy_photo and put images made by this code in the directory. The copy_photo folder is made, so what is wrong in my code? How should I fix this? Am I wrong to write the way of putting images in the copy_photo folder?
find_all_files is a generator. The variable folder_img will be bound to that generator. Calling cv2.imread() on that generator is not going to work because imread() expects an image file, not a generator.
You need to iterate over the generator to copy each file one by one. Something like this:
folder_img = find_all_files(args.input_dir)
for filename in find_all_files(args.input_dir):
im = cv2.imread(filename)
cv2.imwrite(os.path.join(args.output_dir, os.path.basename(filename)), im)
Note also that args.output_dir is a string that represents the desination directory name. You need to specify the path of the file including the directory. Use os.path.join() and os.path.basename() to do that.
If all you are wanting to do is to copy the files from one directory to another then you should perhaps use shutil.copytree as there is no point in opening the image files and then writing them back out. Also, your find_all_files() generator function will pass back all files, including directories, so you need to add some logic to detect image files and filter out those that are unwanted.
cv2.imread() accepts a single file name, but you are calling it with a (generator returning a) list of files.
Try this:
def find_all_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
# Comment out dead code
'''
p=os.path.join(root, file)
p=p.split("/")[len(p.split("/"))-2]
name, ext = os.path.splitext(p)
'''
# Changed this to return a tuple
yield root, file
for dirname, imagefile in find_all_files(args.input_dir):
im =cv2.imread(os.path.join(dirname, imagefile))
cv2.imwrite(os.path.join(args.output_dir, imagefile), im)
Because imwrite() needs to receive a filename parameter, I changed find_all_files to return a tuple, so you can use the same filename for the output, and choose which directory name you add in front.
Rewriting the images seems like a very inefficient way to do this, though. Why don't you simply copy the files?
I'm trying to read a bunch of pgm files for a facial recognition project.
These files lie in an overall folder called "negative" and within the negative folder are subfolders. This portion of my script is supposed to go into all of the directories, store the filenames in an array, and store the "image file" in another array using OpenCV.
os.chdir("../negative")
dirnames = os.listdir(".")
neg_names = []
for i in dirnames:
if os.path.isdir(i):
os.chdir(i)
neg_names.append(os.listdir("."))
os.chdir("..")
face = cv2.imread(i,-1)
faces_negatives.append(face)
print faces_negatives
For some reason when it prints the array I get NONE in every index (there are 40 of them). From my understanding I should be getting binary values from this. This code works file with jpg files.
Just in case anyone else runs into this issue, I found a solution:
I figured out the issue I was having had to do with the path that I was sending into the function "imread". The full path of the file needs to be passed into the function in order for it to read properly. The issue was resolved when I entered in the full path of the image