In both of those countries, the train connections are slower and more tenuous, not sure this is a good way to get those unexpected moments on film. I know what you are talking about in terms of those off-the-beaten-path moments. My wife and I had that in Ireland in 2002, also Portugal in 2008. In both cases we had car, and I think to get that in Spain and Portugal you need a car. The train connections are just not that great. But you may have better luck with busses which supplements the train system especially in Spain.
I have been to both countries, and in my experience the action in Spain is in the cities. We did Spain almost entirely by train, only renting a car for a couple of days to do a side trip to Gibraltar. There is not much in the middle of nowhere that is that rewarding in Spain. In Portugal it is more mixed, you really need to see both. Lisboa is one of the great underrated cities of Europe. That said the train connections are slow and you really need to make it to Evora, Nazarre, and even to Marvao and Tomar. The last two are not in Rick's book but should be. Go on Flickr and search for those places and you will see what I mean. You must also do an overnight in Sintra outside of Lisboa, in my top five magical places in ten trips to Europe. Must is not a word that use a lot in travek advice, but for Sintra it is justified.
Madrid to Lisboa, I would take the overnight train. Any time you get in a plane you are subject to delays, etc. and it's six to eight hours door to door for a one hour flight.
I think what you are after is that sense that you are seeing something that is off the beaten path. There is some of that everywhere for the observant, of course. But for my money, Portugal has more of it than Spain, as much as I love Spain.