The classic approach would be to use sed:
cp "${filename}" "$(realpath ${filename} | sed s:/:__:g)"
The advantage is primarily portability across shells if you won't necessarily always be using bash.
Of course, it also lets you forego the script and just do it with find:
find /base/path -type f -exec cp \{\} `realpath \{\} | sed s:/:__:g` \;
Find has sorting and filtering options you can use if you need them to only copy certain files.
edit: That find setup works on one of my systems, but not on the other one. Rather than sort out the difference, I just made it more portable:
find /base/path -type f | sed -e "p; s:/:__:g" | xargs -n2 cp