I seem to have solved the problem of the webcam stream opening and closing by removing the lines:
stackoverflow.com