You should properly indent your code so you & others can study them comfortably. 
Use this site service for it
Beautifier.io
Back to your code, even though you check img for the 1st image(), the 1 inside your triple loop is missing. 
Actually, you should skip your whole triple for loop if there’s no img. 
Also, you’re loading the p5js libraries 2 times in your “index.html” file! 