In Matt 17:4, how did Peter recognize Moses and Elijah?
There are at least two means by which Peter knew what he otherwise knew not moments prior, that I feel have a great degree of credibility and are less speculative than other suggestions which can be offered in response to your question.
By divine revelation
Peter knew the identities of the two, the same way he knew to answer and say
“Simon Peter replied, "You are the Christ, the Son of the living God."” Matthew 16:16
And Jesus tells him that in no way was the flesh involved in revealing this to Peter but this was spiritually discerned.
“And Jesus answered him, "Blessed are you, Simon Bar-Jonah! For flesh and blood has not revealed this to you, but my Father who is in heaven.” Matthew 16:17
This is done by the very Spirit who knows all things and teaches us on the spot if necessary
“for the Holy Spirit will teach you in that very hour what you ought to say."” Luke 12:12
And the Spirit gives revelations.
“For one who speaks in a tongue speaks not to men but to God; for no one understands him, but he utters mysteries in the Spirit. On the other hand, the one who prophesies speaks to people for their upbuilding and encouragement and consolation.” 1 Corinthians 14:2-3
Peter was made aware of who was who on the mountain, not in any carnal or fleshly way but by the Father into his soul (mind/psyche)
What needs to be emphasized is that the revelation is not at the demand of the human to know but at the Spirit to give, if and when He chooses.
It is possible that Peter deduced from their conversation who was who, especially if their names were mentioned
“And behold, there appeared to them Moses and Elijah, talking with him.” Matthew 17:3
It is hard not to be speculative about how the apostles recognized these men. But there are only a few ways they could have known. 1. They introduced themselves. 2. The Spirit told them. 3. Maybe as Sola mentioned, paints of them.
Some may take this to be hard, but not every second of Jesus's life is recorded in the Bible. It is not a play by play.
I am sure much more happened at this meeting then what is recorded.
I think they simply introduced themselves, just like we do when we meet someone new.