Search code examples
pythonopencvraspberry-piface-detection

Raspberry Pi crashes and reboots when using the Haar Cascade Classifier


I am trying to make a face detector using a new Raspberry Pi 4 Model B. Whenever I run the following code, the Raspberry Pi just shuts down and reboots. I am not sure why at all. How can I fix this?

I first had code to use the camera to do face detection live, but then it would crash. I ended up realising that the face detection line was the issue and wrote this code to perform face detection on a single image to see if it would work. That also ended up making the Raspberry Pi restart.

The code:

import cv2

face_cascade = cv2.CascadeClassifier("haarcascade_frontal_alt.xml")

filepath = "John.jpg"

img = cv2.imread(filepath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.1, 3)

for (x,y,w,h) in faces:
    cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)

cv2.imshow("image", img)
cv2.waitKey(500)
cv2.destroyAllWindows()

The restart happens on the line:

face_cascade = cv2.CascadeClassifier("haarcascade_frontal_alt.xml")

Solution

  • TLDR: check your power supply

    Always I heard about an RPI unexpected shutdown, my first attempt is looking for the Power Supply. It turns out that high CPU bound processing requires a lot of energy to perform and if the PS cannot provide such energy very unpredictable events can happens (see for example this answer where the executable code file is just wiped out because of this).

    In other words, there is nothing in your code explicitly making your RPI to shutdown. But your code is demanding more energy resources than the board is able to deal with.

    Thus, my first advice is checking your power source or power source cord and make sure that RPI 4 power requirements are fit (check here for know the RPI power requirements).

    In addition for the proper RPI PS, I just realized that you are using a camera. Considering that the Camera is USB (not CSI), the power consume by cameras like this can also making a role in your issue. If so, try to use a non-passive USB hub in order to provide the power required for the camera.