factor out image indexing into function