Move each image to its most referenced folder

What I’m trying to do

In my vault I have a bunch of folders and files. Each file has probably at least one image referenced in it but many has several. All these images are by default piled in the root directory of the vault. What I want to do is to move each of these images to the respective folder where it’s referenced the most.

Things I have tried

I have looked for a plugin that can do this without much success. I’ve also started on a bash script but realized my scripting knowledge is limited.

Help

Does anyone have any ideas of how I can accomplish this? Thanks in advance!

I don’t know what plugin or script could achieve this. Most referenced? I think the image can be anywhere. The important thing is the markdown file containing the reference.

If you are bothered by the fact the images are dumped together in the root folder, you can set a folder below each folder with a name like attachments, assets, resources, media, images, etc.
See in my case:

There was also a similar thread in the past: