Try to init capture several times

Change-Id: Id951a2a104d9e8c44e38394e6e80993723dd5bdd
diff --git a/vision.py b/vision.py
index 3c042cf..8469a79 100644
--- a/vision.py
+++ b/vision.py
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import sys
+
 import cv2
 import numpy as np
 import tflite_runtime.interpreter as tflite
@@ -73,15 +75,29 @@
 
 def get_frames(title='Raspimon camera', size=(640, 480)):
   width, height = size
-  cap = cv2.VideoCapture(0)
+
+  attempts = 5
+  while True:
+    cap = cv2.VideoCapture(0)
+    success, _ = cap.read()
+    if success:
+      break
+
+    if attempts == 0:
+      print("Cannot initialize camera!", file=sys.stderr)
+      sys.exit(1)
+
+    cap.release()
+    attempts -= 1
+
   cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
   cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
   while True:
-    ret, frame = cap.read()
-    frame = cv2.flip(frame,1)
-    if ret:
+    success, frame = cap.read()
+    frame = cv2.flip(frame, 1)
+    if success:
       yield frame
-    cv2.imshow(title, frame)
+      cv2.imshow(title, frame)
     if cv2.waitKey(1) & 0xFF == ord('q'):
       break
   cap.release()