The automatic pain detection in the context of clinical settings and treatment interventions offers promising opportunities for pain management and treatment optimization. While subjective self-reports and clinical observers are often convenient and useful in quantifying pain, automatic pain detection systems can provide a continuous, more objective and consistent measure of pain. This can also greatly reduce efforts in large-scale studies, where it may be highly impractical and inefficient to conduct clinical interviews and questionnaires. To address this, we propose a novel machine learning method based on deep neural networks trained to automatically detect pain onset/offset and its intensity from facial expressions of participants receiving nociceptive stimuli. To train the network, we used the publicly available UNBC-McMaster Shoulder Pain Expression Archive Database, annotated in terms of the Prkachin and Solomon pain scale. We report the performance of our algorithm in a single-center, comparative, randomized, crossover, clinical study that evaluates the impact of different injection parameters on subcutaneous injection pain tolerance.