In the UK, you remove your hat -

When passing or being passed by a funeral cortège (one also stops walking and stands still).

When walking through a lychgate at the entrance to a churchyard. Not necessarily in the churchyard itself.

When one is part of a funeral procession. Mourners, following the coffin are bare headed, but the gravediggers, (standing to one side, waiting for the internment to finish) are not.

Regards

Chas