6
\$\begingroup\$

I have been working on a simple Python application for face recognition with OpenCV. My code does its work and gets the job done, but I'm wondering if there's a 'better' way to do this. I hope I can get some tips on how to structure or approach this task.

See my full code 1 and 2.

while True:
 (_, im) = webcam.read()
 gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
 persons = face_cascade.detectMultiScale(gray, 1.3, 5)
 for (x,y,w,h) in persons:
 cv2.rectangle(im,(x,y),(x + w,y + h),(0, 255, 255),2)
 face = gray[y:y + h, x:x + w]
 rescaling_the_face = cv2.resize(face, (width, height))
 prophecy = model.predict(rescaling_the_face)
 cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 255), 2)
 if prophecy[1]<400:
 cv2.putText(im,'%s' % (names[prophecy[0]]),(x + 10, (y + 22) + h), cv2.FONT_HERSHEY_PLAIN,1.5,(20,205,20), 2)
 else:
 cv2.putText(im,'STRANGE_PERSON',(x + 10, (y + 22) + h), cv2.FONT_HERSHEY_PLAIN,1.5,(65,65, 255), 2)
 cv2.imshow('OpenCV Face Recognition - esc to close', im)
 key = cv2.waitKey(10)
if key == 27:
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 12, 2017 at 17:26
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Some notes only:

Instead of

(_, im) = webcam.read()

is more common not to use parentheses:

_, im = webcam.read()

(and similarly in other places of your code).


Too many blank lines. In the PEP 8 - Style Guide for Python Code repeatedly occurs the word "sparingly" for the Blank Lines usage.


(Correcting English only):

Instead of

print("Webcam is open? ", webcam.isOpened())

use

print("Is the webcam open? ", webcam.isOpened())

Magic numbers in your code, as in this statement

if key == 27:

Why not use names for such constants, e. g.

ESC_KEY = 27 # Near the start of your code
...
...
if key == ESC_KEY:
answered Aug 12, 2017 at 19:58
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.