The cerebral cortex is spontaneously active, but the function of this ongoing activity remains unclear. One possibility is that spontaneous activity provides contextual information in cortical computations, replaying previously learned patterns of activity that conditions the cortex to respond more efficiently, based on past experience. To test this, we measured the response of neuronal populations in mouse primary visual cortex with chronic two-photon calcium imaging during a visual habituation to a specific oriented stimulus. We unexpectedly found that, during habituation, spontaneous activity increased in neurons across the full range of orientation selectivity, eventually matching that of evoked levels. The increase in spontaneous activity strongly correlated with the degree of habituation. In fact, boosting spontaneous activity with two-photon optogenetic stimulation to the levels of stimulus-evoked activity induced habituation in naive animals. Our study shows that cortical spontaneous activity is causally linked to habituation, which unfolds by minimizing the difference between spontaneous and stimulus-evoked activity levels, rendering the cortex less responsive. We also show how manipulating spontaneous activity can accelerate this type of learning. We hypothesize that spontaneous activity in visual cortex gates incoming sensory information.