Home Creators Posts Import Register Favorites Logout

Downloads

Content

DeepFace and RetinaFace script that sorts AI generated images by similarity to your original photos so you can find the best ones; replaced by a newer app.

Note: this is an older post kept for reference. The current, maintained version is DeepFace Face Similarity Sorter: 1-Click Batch Image Sorting App.

The older scripts (findBestImagesV4 with RetinaFace face detection) run on Windows with CPU or GPU venvs and on RunPod, and can append model, clip skip and LoRA info to file names. The post itself says it is deprecated in favor of the DeepFace batch face similarity sorting Gradio app.

With DeepFace & RetinaFace libraries we will sort AI generated images with best accuracy to your original. Thus, you can find best ones

this post is deprecated new app is here : https://www.patreon.com/posts/121335747

https://www.patreon.com/posts/121335747

new app is here : https://www.patreon.com/posts/121335747

new app post : https://www.patreon.com/posts/121335747

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

Patreon exclusive posts index to find our scripts easily, Patreon scripts updates history to see which updates arrived to which scripts and amazing Patreon special generative scripts list that you can use in any of your task.

Join discord to get help, chat, discuss and also tell me your discord username to get your special rank : SECourses Discord

Please also Star, Watch and Fork our Stable Diffusion & Generative AI  GitHub repository and join our Reddit subreddit and follow me on LinkedIn (my real profile)

=======

Super Important Windows Requirements

  • Python 3.10, FFmpeg, CUDA 12.4, cuDNN 8.9 or above, C++ tools and Git

  • If it doesn't work make sure to below tutorial and install everything exactly as shown in this below tutorial

  • https://youtu.be/DrhUHnYfwC0

30 January 2025 Update:

  • All files put into single zip file sort_by_similarity_v2.zip

  • Tested and verified

  • Ignore the confliction errors you get at the end

  • pip freeze info added

  • findBestImagesV4 .py is the latest version

  • run .bat file will use findBestImagesV4 by default

  • do not forget to change image folders before execute run .bat file

  • Requirements python 3.10.x - I prefer 3.10.11 version

23 November 2023 Update:

  • runpod_installer. sh updated to support GPU on RunPod - reinstall

  • Now many times faster

  • Don't forget to execute

  • apt update

  • yes | apt install -y libcudnn8=8.9.6.50-1+cuda11.8 libcudnn8-dev=8.9.6.50-1+cuda11.8 --allow-change-held-packages

1 October 2023 Update:

If you get zlib error put also zlibwapi.dll into the folder

  • findBestImagesV4 .py added to the scripts. This new version will use RetinaFace library to find faces

  • With this upgrade, it will find faces with much much better accuracy than before

  • run .bat file will run findBestImagesV4 .py by default

  • Also we upgraded to extract_faces method from deprecated detectFace method

30 September 2023 Update:

  • Auto installers for Windows added

  • install-cpu .bat file will compose a venv and install. This venv will use CPU

  • install-gpu .bat file will compose a venv and install. This venv will use GPU

  • Edit run. bat file to make it run findBestImagesV3. py

  • findBestImagesV3. py file will run as a single thread. If you use CPU you can increase number of threads

July 7 Update: RunPod installer and instructions are added.

Tutorial video : https://www.youtube.com/watch?v=343I11mhnXs

Script file and PDF file updated. Script has been improved.

If you upvote our reddit thread I would appreciate that very much : https://www.reddit.com/r/DreamBooth/comments/137zesc/novel_how_to_find_best_stable_diffusion_any_ai/

Download the attached files findBestImages .py

Follow the tutorial to use the script

Please comment and ask me any questions. I can also improve the script based on your needs.

12 May 2023

1 August 2023 - improved

Upon a request of one of your beloved supporters I have added findBestImagesV2 .py

findBestImagesV2 .py Will append model name, skip clip count (if only above 1) and used lora info to the image name. E.g. V2 file name : 1 - 0.266 - deliberate_v2, Clip skip 2 -lora-256rank-000007-1-

Auto Installer For RunPod

Each time you restart RunPod or turned it off and turned it on 1 time below command

  • apt update

  • yes | apt install -y libcudnn8=8.9.6.50-1+cuda11.8 libcudnn8-dev=8.9.6.50-1+cuda11.8 --allow-change-held-packages

Download and upload runpod_installer .sh into workspace

Then run below commands

  • chmod +x runpod_installer.sh

  • ./runpod_installer.sh

For using you need to activate first. Execute below command

  • source deep_face_venv/bin/activate

  • python findBestImagesV4.py

Don't forget to edit folder paths accordingly to RunPod

Such as

  • org_images_folder_path = r"/workspace/org"

  • generated_images_folder_path = r"/workspace/generated"

  • detected_faces_folder_path = r"/workspace/detected"

  • -

  • -

Related posts

All posts in this topic: Captioning, Dataset and Image Processing Tools · New to SECourses? Start Here: Best and Most Popular SECourses Posts

Files

Comments

Raf Stahelin

How do you sort the images by rank of likeness? The filenames are saved with decimal rank after image number, so you cannot sort by rank...

SECourses

that is actually their rank. so the most similar one, which has least distance, gets the number 1. so the least distance is the most likeliness. those seconds values are the distances not similarity. the algorithm calculate distance.

Raf Stahelin

Oh I see. Sorry for the trouble

Anthony Therrien

It appears that as the number of pictures to process increases, the script's performance slows down. My test results indicate that processing 2500 pictures took about 7 hours, while processing only 400 pictures took about 7 minutes or less. It's not related to termal.

Anthony Therrien

I can send you an improved version, but it's only an half fix. I process them in batch of 400 with my wrapped code.

SECourses

yes it can be even improved with expanding multi threading. if you send me i can test and update the script. if you need i can also try to make it even more multi-threading.

SECourses

it should increase linearly. are you sure about this? i will check and see if there is a memory leak or something

Anthony Therrien

I have created an optimized version of the code using multi-threading. I will send you the code via inbox.

SECourses

Thank you so much I will update the script with yours

G.J. Radsma

hi! "Function detectFace is deprecated! Use extract_faces instead of this." the script functions as normal? but is there and advantage to use the current method?

SECourses

well i think not. because that part is only used for small purpose seeing how our original images are performing. original comparison function is the correct and up-to-date one.

Ec Jep

I changed by default installation from python 3.10.6 to 3.10.9, deleted original venv folder and recreated venv folder and ran pip install deepface. After doing these steps it now says this error : ModuleNotFoundError: No module named 'matplotlib' Can you help me figure out what I did wrong?

SECourses

can you activate venv and run this and let me know? : pip install matplotlib

Ec Jep

thanks for the quick feedback! That worked and now its back up and processing...

Khang

Thank you for adding Runpod installer.

SECourses

You are welcome. Thanks for comment

JoeMarcus

Not fully related but does anyone know of a tool that do this to music? To sort music with this level of AI involvement?

SECourses

nice idea. so you want to sort similar songs. i should look for this. what is your purpose for this?

JoeMarcus

To better sort my folders of music I use to dj

SECourses

I see. so you want to give base music files and you want others to be sorted based on similarity. i should do a research for this.

rawdirt

I don't understand how to download the images.. The runpod installer wont generate any directory named deepface therefore I cant runt the findBestImages.py script. any help appreciated! :)

SECourses

hello. this script is used for this task. lets say you have trained yourself and then you generated your trained self. like 1000 images. then you can use this script to sort them with similarity to your training original images. thus you can quickly find best looking images if you can elaborate more what you are asking i can give you more precise answer. to make this script work please watch the tutorial. if you also can raise donation to 25$ i can connect your pc (e.g. via anydesk or google remote) and install and explain to you. but i have to sleep today so hopefully i can do that tomorrow

rawdirt

Hi! :) Ah no I’m not actually trying to use the deepface script, just download the big image library of people/faces for som Kohya lora training

Broadband

I'm noticing a few issues with the V2 script that's listed 1) It stops after 4 images. Looking at line 96 it appears to be hard coded to stop at 5. counter += 1 if counter == 5: break It should be: if counter > num_files: 2) It renames all files as .png even if the file is in jpg format. It also fails to find model info if it's a jpg and leaves a blank space in the requirements. new_filename = f"{formattedScore} - {modelname} - {i+1}.jpg" can be changed to: if filename.endswith('.jpg'): new_filename=f"{{formattedScore}- {i+1}.jpg" if filename.endswith('.png'): new_filename=f"{formattedScore} - {modelname} - {i+1}.png" 3) It seems to fail if any original images can't have faces detected. Not sure how to just skip the file and continue

rawdirt

Awesome. No problem :) Thank you very much!

SECourses

all valid points. 1 : increased it to 5000. it is an hard coded limit. it exists because lets say you have 1m images and you only want to sort first 5000. it will not continue once finished all images 2 : fixed. now even supports webp as well. it will keep same file extension 3 : it skips and don't use image if fails to detect face. tested and verified

SECourses

you are welcome and thanks a lot for support

MathiasF

Hi, maybe I'm to stupid ;-) what is the right way to preserve the original filename in the finally sorted files. E.G "1 - 0.123.png" should be "1-0.123-originalname.png" I tried to change new_filename = f"{i+1} - {formattedScore} - {modelname}{file_extension}" to new_filename = f"{i+1} - {formattedScore} - {modelname}-{filename}{file_extension}" but this did not work

SECourses

here the code: original_filename_without_extension = os.path.splitext(os.path.basename(filename))[0] new_filename = f"{i+1} - {formattedScore} - {modelname} - {original_filename_without_extension}{file_extension}"

theunlikely

Could this be good for testing epochs of lora training? Or maybe even lora block weights?

SECourses

100% can be good because this pretty much evaluates how resembling the produced results are.

Ran Bensimon

Can this work with styles as well? for example, a clothing that I trained?

SECourses

This is only for sorting by face similarity. What is your purpose I may give you direction

Ran Bensimon

Yes I tried on face and it's amazing! My purpose is to train a bodysuit, so I created xyz plot with 800 images and I want to sort the best ones by using 1 image from the images I trained. A specific style.

benjamin macauley

Thanks for this. I do these for my friends so I see so many slight variations of them that I forget what they actually look like

SECourses

ah i see. so sorry for late reply i didnt get notification. this script only sorts by face :/

Khang

I think that there is something wrong with the image name. After the process is done, I download the images but I can't open some images in some softwares such as BooruDatasetTagManager or Runpod. It only happens to some images whose names are changed. One example is "2 - 0.351 - sd_xl_base_1.0, Lora hashes V59-N01-mm-woman-000110 db01963f91d4, V56-N07-Merge_n05e200_n06e200_p100p100 bf404c5f89cb, Version v1.5.1 -lora-V59-N01-mm-woman-000110-1-.png" (its name is long because I used a merge Lora or multiple Loras) If I use the original name of the image which is "000123.png" then nothing happens. Not sure why, name is too long, special characters??

Khang

Also when the process is done it shows many errors, I check 800+ images but it can only show me 200 images. The other 600 images' name can't be changed so what should I do now? Error occurred while processing /workspace/_generated/00256-3994657596.png: [Errno 36] File name too long: '/workspace/_generated/00256-3994657596.png' -> '/workspace/_generated/785 - 0.712 - sd_xl_base_1.0, Lora hashes V59-N11-mm-woman-000140 72ff4adda98b, V59-N01-mm-woman-000140 70b5bc700809, V58-N01-QUALITY-Control-n1e160_n100 61f13329927c, V61-N01-tt-outfit-000120 2f5bf2f73941, Version v1.5.1 -lora-V59-N11-mm-woman-000140-0-.png' Error occurred while processing /workspace/_generated/00232-4167073968.png: [Errno 36] File name too long: '/workspace/_generated/00232-4167073968.png' -> '/workspace/_generated/798 - 0.759 - sd_xl_base_1.0, Lora hashes V59-N11-mm-woman-000140 72ff4adda98b, V59-N01-mm-woman-000140 70b5bc700809, V58-LORA-2sq-image_V58-N01_V58-N01-2sq-image-000200 a4d17768969b, V61-N01-tt-outfit-000120 2f5bf2f73941, Version v1.5.1 -lora-V59-N11-mm-woman-000140-0.4-.png'

SECourses

yes name is too long. can you use findBestImagesV3.py it is handling too long names. sorry for late reply

SECourses

yes name is too long. can you use findBestImagesV3.py it is handling too long names. sorry for late reply

Khang

Hi Dr. Furkan, thank you for updating your V3 script; it works great. May I ask two questions: 1. When I run the script and SD to generate new images at the same time, SD shows this error: "OutOfMemoryError: CUDA out of memory. Tried to allocate 512.00 MiB (GPU 0; 23.69 GiB total capacity; 8.70 GiB already allocated; 134.06 MiB free; 9.41 GiB reserved in total by PyTorch)." Is there any way to solve this so I can generate and rate images at the same time to save time? (I use RTX 3090 on Runpod.) 2. Is there any way to only search for and rate new images in a folder (and also in its subfolders), ignoring images that have already been rated in a that folder? I want to use the generated_images_folder_path = r"/workspace/stable-diffusion-webui/outputs/txt2img-images" so that whenever I run your script, it could check new images that are just created by SD without me having to copy and paste those images to the _generated folder multiple times. Currently, I can't do that for two reasons: - It may re-rate old images again. - When it runs three times, there would be three 1st rank images. I just want it to add image point, no need for rank. (I think I should delete the f"{i+1}" part and keep only the "{formattedScore}" part in new_filename, right?) Actually, I don't like the RANKING part because I have to wait for it to finish all 1000 images to know the results. If something happens during this time then I have to do it all over again. I'd prefer it to rate each image and edit the name immediately so I can collect good images as soon as possible. Is that possible?

SECourses

1 : you can start machine with dual gpu and use 1 gpu on 1 and use another gpu on script 2 : requires a lot of coding. if you could upgrade your membership to 50$ for only 1 time (after paid degrade back to 5$) i could work on changes you need. ty so much

Khang

Thank you for your quick response. I want to ask if this code is for the FACE ONLY? I noticed that the folder _detected has images of faces with CROPPED CHIN or CROPPED FOREHEAD. So, the results could show a similar face but with a different HEAD SHAPE (head too long/short or rectangular/circular). Is there any way to check the head shape too? Also, how do I change the code so that it can change the name of each image when that image is rated? (Just add a point to its name, I have no need to rank it since I can sort by its name later). Currently, I have to wait for all 1000 images to finish rating to know the result. If something happens during that time or I want to stop halfway, then I have to do it all over again.

SECourses

there is no head cropper as far as i know. so only way is expanding detected face or training a custom model yourself i would ask GPT4 for changes. really good can help you significantly

Rabadan

PS D:\deep_face> .\run.bat Detecting faces in the given original training images folder... ⚠️ Function detectFace is deprecated! Use extract_faces instead of this.

SECourses

ye it is fine. working good atm.

SECourses

I just made updates. huge improvement. reread and redownload.

Rabadan

I'm running the new version here, however I noticed that it is not using the GPU, but only the CPU, which makes the process of analyzing a larger volume of images very slow. What can I do to make the script use the GPU? Thanks!

SECourses

what GPU you have? I have added use GPU installer. you need to do a fresh installer with that - install-gpu.bat

Rabadan

I´m using a rtx4090. Strangely enough, v3 runs much faster, and with significant GPU usage graphics, while V4 is much slower and CPU intensive, and shows no signs of consuming the GPU.

SECourses

well i think CPU version could be working better due to how DeepFace library is optimized. So use whichever is faster :D

Arcon Septim

Very useful for professional use

Mig Test

In my case, the issue was one of missing dependencies. I had to install CUDA Toolkit 11.8 and cuDNN 8.9 for CUDA 11.x. Thereafter, the script now hits the GPU and goes much, much faster.

Mig Test

I should also note, I already had CUDA 12.2 install, and was able to install 11.8 alongside without uninstalling 12.2.

Joosheen

Hello ;) install-gpu.bat is not working.. there are conflicts between keras, protobuf, tensorflow and tensorflow-estimator. I have screens of these errors but here is no option to make an attachment.. installer is closing right after error

SECourses

are you using python 3.10? i am doing a fresh install right now to fix if broken

Joosheen

yes, python 3.10.11

SECourses

hello. i just did a fresh install. got same errors. but ignore them safely. working blazing fast with 0 errors. just proceed to usage

Joosheen

hmm, i got messages that it doesnt recognize face from my original files. I thought its because of errors. Do you have the same that installer is closing right after this error?

SECourses

yes same. it also same way turned off. can you message me from discord and show me your reference image and ai images? also what do you see on cmd when you run the script?

Joosheen

ok, so im going to discord

chriseppe

did you use it for testing epochs? If yes, how well did it work and what did you do? :)

Josh Tech

If we disregard the time for the scan, is it better to: 1. to take fewer original images with relatively similar facial expressions because, for example, a strongly lowered gaze distorts the result? 2. to take more images because the greater variance generally leads to a better result? Thank you for your answer

Josh Tech

Another question. I get the following error for 10% of my generated images on RunPod: "Error occurred while processing /workspace/generated/a_244.jpg: Exception while processing img2_path". They are all jpg with same dimensions. Do you have any idea what causes this problem?

SECourses

well i think you can also use 1 image that you like most. but the program will take average

SECourses

that image probably corrupted. you can delete it and continue.

trsh3r

Hi Furkan. I've been trying to install this one, but I keep getting errors. - Installing for CPU seems to work fine (besides fire deprecation msg and a notice to upgrade pip from 23.0.1, but assume these are normal?), but on run, I get a No module named 'tf_keras' error msg. I tried running `pip install tf-keras` as prescribed but doesn't solve the issue (getting a requirement already satisfied). - Installing for GPU doesn't even get there: I get dependency resolver error (again re keras and tf, adding protobuf and tensorboard version issues) When running, I just get 'The image is not detectable as a face' error on all my pictures. I run Python 3.10.11 / CUDA 11.8, installed following your tutorial :) Thank you for your help!

trsh3r

This is the error msg when running CPU install Traceback (most recent call last): File "D:\_misc APPS\Checker\venv\lib\site-packages\retinaface\commons\package_utils.py", line 19, in validate_for_keras3 import tf_keras ModuleNotFoundError: No module named 'tf_keras' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\_misc APPS\Checker\findBestImagesV4.py", line 2, in from deepface import DeepFace File "D:\_misc APPS\Checker\venv\lib\site-packages\deepface\DeepFace.py", line 20, in from deepface.modules import ( File "D:\_misc APPS\Checker\venv\lib\site-packages\deepface\modules\modeling.py", line 16, in from deepface.models.face_detection import ( File "D:\_misc APPS\Checker\venv\lib\site-packages\deepface\models\face_detection\RetinaFace.py", line 3, in from retinaface import RetinaFace as rf File "D:\_misc APPS\Checker\venv\lib\site-packages\retinaface\RetinaFace.py", line 20, in package_utils.validate_for_keras3() File "D:\_misc APPS\Checker\venv\lib\site-packages\retinaface\commons\package_utils.py", line 24, in validate_for_keras3 raise ValueError( ValueError: You have tensorflow 2.17.0 and this requires tf-keras package. Please run `pip install tf-keras` or downgrade your tensorflow.

trsh3r

and when running GPU install: ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. tensorflow-intel 2.17.0 requires keras>=3.2.0, but you have keras 2.10.0 which is incompatible. tensorflow-intel 2.17.0 requires protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3, but you have protobuf 3.19.6 which is incompatible. tensorflow-intel 2.17.0 requires tensorboard<2.18,>=2.17, but you have tensorboard 2.10.1 which is incompatible. Successfully installed cachetools-5.5.0 gast-0.4.0 google-auth-2.34.0 google-auth-oauthlib-0.4.6 keras-2.10.0 keras-preprocessing-1.1.2 oauthlib-3.2.2 protobuf-3.19.6 pyasn1-0.6.1 pyasn1-modules-0.4.1 requests-oauthlib-2.0.0 rsa-4.9 tensorboard-2.10.1 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.1 tensorflow-estimator-2.10.0 tensorflow-gpu-2.10.0

SECourses

gpu works ignore those. i just had same but works perfect

trsh3r

tried another install, and I still get 'The image is not detectable as a face' error on all my sample pictures. I've tried using about 100 different (portrait) pictures now, and none of them is detected :(

trsh3r

thank you I'll give it a try