# Is it a coincidence that quantum harmonic oscillators and photons have energy quantised as $E=hf$?

I have studied the quantum harmonic oscillator and solved the Schrodinger equation to find the eigen-energies given by

$$E_n = \left(n+\frac{1}{2}\right)\hbar \omega.$$

Which means the energy levels are separated by

$$\Delta E = \hbar \omega = hf$$

I have also studied blackbody radiation and one of the assumptions Planck made was that the energy levels accessible to the cavity oscillators are separated by this same amount $\Delta E$. This makes sense to me as the source of blackbody radiation is just an oscillator in the wall so I can see the connection between a quantum harmonic oscillator and a cavity oscillator. However a photon that is emitted when an electron transitions between energy levels in an atom is not due to any oscillators, is it just a coincidence that the energy of a non-blackbody photon is given by $E = \hbar \omega$ or is there some connection between photons and oscillators?

It's not a coincidence! You can see the reason even in classical mechanics: if you take a charge and shake it sinusoidally at frequency $\omega_q$, it makes light with equal frequency $\omega_{\gamma} = \omega_q$.
If you quantize light wave emission into individual photons, so that $E = \hbar \omega_{\gamma}$, the spacing between harmonic oscillator energy levels must be $\hbar \omega_{\gamma}$. But since $\omega_\gamma = \omega_q$, this is equal to $\hbar \omega_q$, so $$E_n = n \hbar \omega_q + \text{const.}$$ as you observed.
A photon is produced by a transition between two levels and by definition of "photon" its energy is $h\nu$, where $\nu$ is the frequency of the classical electromagnetic wave that will emerge from a great number of the same energy photons. So it is a matter of coincidence only because Maxwell's equations have sinusoidal solutions for the electromagnetic waves and the harmonic oscillator has a frequency connected with the classical potential. The harmonic potential is one of the possible potentials entering quantum mechanical equations.
In fact you can think of freely propagating electromagnetic field as an infinite set of harmonic oscillators. To see this, note that (with appropariate choice of unit system) energy density of electromagnetic field is proportional to $\vec E ^2 + \vec B ^2$. This expression is sum of two quadratic terms, which closely resembles Hamiltonian of harmonic oscillator. Except that you actually have an infinite ensemble of harmonic oscillators, because electromagnetic field depends on continuous variable $\vec x$. Equivalently, field can be decomposed as superposition of plane waves, with wave vector $\vec k$. So you can consider field as ensemble of oscillators, labeled by index $\vec k$.