Python Face-Recognition - Search Folder of multiple images for match - python

I have the following code:
import face_recognition
from PIL import Image, ImageDraw
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from shutil import copyfile
#Ask user for file name
Tk().withdraw()
filename = askopenfilename()
#Add known images
image_of_person = face_recognition.load_image_file(filename)
person_face_encoding = face_recognition.face_encodings(image_of_person)[0]
for i in range (1, 8):
#Construct the picture name and print it
file_name = str(i).zfill(5) + ".jpg"
print(file_name)
#Load the file
newPic = face_recognition.load_image_file(file_name)
#Search every detected face
for face_encoding in face_recognition.face_encodings(newPic):
results = face_recognition.compare_faces([person_face_encoding], face_encoding, 0.5)
#If match, show it
if results[0] == True:
copyFile(file_name, "./img/saved" + file_name)
The intention is to use the known image (image_of_person) and search a folder of images ('./img/unknown') for a match, then show the matched photo.
I receive the error:
No such file or directory: '00001.jpg'
On the line
newPic = face_recognition.load_image_file(file_name)
How do I point the recognition to the sample of images folder?
Note: for i in range (1, 8): - 8 Images are in the sample folder.

I think your problem is you're not giving the right path when trying to load the images.
Change
file_name = str(i).zfill(5) + ".jpg"
to
file_name = f"./img/unknown/{str(i).zfill(5)}.jpg"
Note: If you're using python2, then
file_name = "./img/unknown/{}.jpg".format(str(i).zfill(5)
Another tip, if you want your code to be generic, no matter how many images there are, you can do
for i in range(1, len(os.listdir("./img/unknown"))).
Or, even better, you can simply do
for img in os.listdir("img/unknown"):
file_name = os.path.join("img/unknown", img)
... continue with the rest of the flow ...

Related

How can I save images with different name on different directory using PIL .save?

I'm trynna get the train_img and ground truth img from directory './train_dataset/train_img_cropped' & './train_dataset/train_gt_cropped'. Next, I wanna save the both original image and flipped one with a '_0', '_1'tail on its name in directory './train_dataset/train_img_preprocessed' & './train_dataset/train_gt_preprocessed'. But there's an Error of changing names (file + "_0" or "_1") as an unknown file extension. Looks like somehow PIL recognizes _0, _1 as a extension. Is there anybody who can help me to save with changing the name?
import os
import os.path
import glob
from PIL import Image
def preprocess(img_path, save_path):
targetdir = img_path
files = os.listdir(targetdir)
format = [".png"]
for (path, dirs, files) in os.walk(targetdir):
for file, i in files:
if file.endswith(tuple(format)):
image = Image.open(path + "/" + file)
image.save(save_path + "/" + file)
flippedImage = image.transpose(Image.FLIP_LEFT_RIGHT)
flippedImage.save(save_path + "/" + file)
print(file + " successfully flipped!")
else:
print(path)
print("InValid", file)
if __name__ == "__main__":
train_img_cropped_path = './train_dataset/train_img_cropped'
train_img_preprocessed_path = './train_dataset/train_img_preprocessed'
train_gt_cropped_path = './train_dataset/train_gt_cropped'
train_gt_preprocessed_path = './train_dataset/train_gt_preprocessed'
preprocess(train_img_cropped_path, train_img_preprocessed_path)
preprocess(train_gt_cropped_path, train_gt_preprocessed_path)
Not sure if this answers your question, but why not save the image with a temporary name (something like a random alphanumeric string or uuid) and then use os.rename to change the name of the temp file with your desired name ending _0 or _1.

Python Iterate through every files in the folder to cut portion of video

I was cropping about hundreds of videos to crop the first 30 seconds of each clip. The code is working for one clip but when I put path, the code starts to not work.
I pasted the current code with what I tried below. Could I get an insight on how I could iterate every file in the folder?
Thank you
import os
import ffmpeg
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
from moviepy.editor import *
def timeCrop():
directory = "/Users/documents/lab/video/ProccessedVideo"
count = 1
for filename in os.listdir(directory):
if filename.endswith(".mpg") or filename.endswith(".mp4"):
path = os.path.join(directory, filename)
input = ffmpeg.input(path)
print(path, count)
mice = ["022, 90"]
ffmpeg_extract_subclip("{path}.mpg", 30, 120, targetname="{mice[0]}.mpg, {mice[1]}.mpg")
count += 1
def timeCrop2():
directory = "/Users/documents/lab/video/ProccessedVideo"
clip = VideoFileClip("022.mpg").cutout(0, 30)
clip.write_videofile("022e.mpg", codec="libx264")
#timeCrop()
timeCrop2()
You can iterate each files in the directory with filter for example (.mp4) using the code below
import os
directory = os.fsencode("D:\\Acroyoga")
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".mp4"):
print(filename) #do your video process here
continue
else:
continue

How do I keep the file name of an image when resizing it and saving it to another folder?

I'm in an introductory neural networking class so mind my ignorance. Also my first SO post.
I'm trying to resize some very highly resolved images within a dataset into 80x80p grayscale images in a new dataset. However, when I do this, I'd like to keep the filenames of each new image the same as the original image. The only way I know how to resave images into a new file is through a str(count) which isn't what I want. The filenames are important in creating a .csv file for my dataset later.
The only SO post I can find that is related is this:
Use original file name to save image
But the code suggested there didn't work - wasn't sure if I was going about it the wrong way.
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
img_resized.save(path2 + str(count) + '.png')
count +=1
pass
pass
Reuse the original filename that you get from the for loop i.e. file
and, split it into filename and extension using os.path.splitext() like below:
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
# splitting the original filename to remove extension
img_filename = os.path.splitext(file)[0]
img_resized.save(path2 + img_filename + '.png')
count +=1
pass
Another option, we can use python str's built-in split method to split the original filename by . and discard the extension.
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
# splitting the original filename to remove extension
img_filename = file.split(".")[0]
img_resized.save(path2 + img_filename + '.png')
count +=1
pass
So, if an image has a name such as some_image.jpeg then, the img_filename will have a value some_image as we splitted by . and discarded .jpeg part of it.
NOTE: This option assumes the original_filename will not contain any . other than the extension.
I assume that image name is on path1. If so you can grap image name from there in this way:
x=path1.rsplit('/',1)[1]
We are splitting path1 on last slash and taking image name string via indexing.

How to save images in a folder with for loop?

First, I have an issue with saving up every resized file with the same name to the same folder? Second, while running I can't understand if m t code works properly. Please, could you check if I am doing the resizing properly?Can't find a mistake in my code:
import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
for image in images:
with open(image,"rb") as file:
img = Image.open(file)
imgResult = img.resize((800,800), resample = Image.BILINEAR)
imgResult.save('"C:/Users/marialavrovskaa/Desktop/Images/file_%d.jpg"', 'JPEG')
print("All good")
If you want to give the images a name with a consecutive number than you've to concatenate the file name and a counter:
image_no = 1
for image in images:
# [...]
name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
imgResult.save(name, 'JPEG')
image_no += 1
Since the format of the images is PNG and they should be stored as JPEG, the format has to be convert from RGBA to RGB, by .convert('RGB'). Note, storing a RGBA image to 'JPGE' would cause an error:
import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
with open(image,"rb") as file:
img = Image.open(file)
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = 'C:/Users/marialavrovskaa/Desktop/Images/file_' + str(image_no) + '.jpg'
imgResult.save(name, 'JPEG')
image_no += 1
print("All good")
By the way, if the file name should by kept and the image just should be stored to a file with a different extension, then then extension can be split form the file by .splitext:
import os
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
name = os.path.splitext(image)[0] + '.jpg'
imgResult.save(name, 'JPEG')
If you wan to store the fiel to a different path, with a different extension, then you've to extract the fiel name from the path.
See os.path. Split the path from the file name and extension by os.path.split(path), which returns a tuple of path and name.
e.g.
>>> import os
>>> os.path.split('c:/mydir/myfile.ext')
('c:/mydir', 'myfile.ext')
The split the file name and the extension by os.path.splitext(path):
>>> os.path.splitext('myfile.ext')
('myfile', '.ext')
Applied to your code this means, where file is the path, name and extension of the source image file:
import glob
from PIL import Image
images = glob.glob("C:/Users/marialavrovskaa/Desktop/Images/*.png")
image_no = 1
for image in images:
with open(image,"rb") as file:
img = Image.open(file)
imgResult = img.resize((800,800), resample = Image.BILINEAR).convert('RGB')
image_path_and_name = os.path.split(file)
image_name_and_ext = os.path.splitext(image_path_and_name[1])
name = image_name_and_ext[0] + '.png'
file_path = os.path.join(path, name)
imgResult.save(file_path , 'JPEG')
image_no += 1
print("All good")

Python Pillow resize images trouble: it runs well but there're no images

I'm learning Python and try to use Pillow to resize images in a folder, then save them to another folder with the same filename. However, the program runs well, when I check the destination folder, there're no images...
My code is as below:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for XXPNG in img_list:
fn = os.path.basename(XXPNG)
im = Image.open(XXPNG)
print(fn, im.size)
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save("dst_path","PNG")
print("Resize Done")
Please help me find my bug, or give my any advise.
Thank you very much for help and bearing my poor English.
"dst_path" with " is a normal text, not variable dst_path - so you save in file with name "dst_path".
You need dst_path without " - plus filename
nim.save(dst_path + fn, "PNG")
or with os.path.join()
nim.save(os.path.join(dst_path, name), "PNG")
Code:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for fullpath in img_list:
name = os.path.basename(fullpath)
im = Image.open(fullpath)
print(name, im.size, '=>', os.path.join(dst_path, name))
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save(os.path.join(dst_path, name), "PNG")
#nim.save(dst_path + name, "PNG")
print("Resize Done")

Categories