HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Program for face recognition

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
recognitionfaceprogramfor

Problem

I have been using the following script for face recognition as a security feature:

main.py

```
from itertools import izip
from PIL import Image
def compare(self,pic):
i1 = Image.open("pic1.jpg")
i2 = Image.open(pic)
size = i1.size
i2 = i2.resize(size)
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."

pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] i1.size[1] 3
print ((dif / 255.0 * 100) / ncomponents)
return (dif / 255.0 * 100) / ncomponents

def password(self):
import passw
y=str(self.password_input.text)
x=passw.verify(y)
if x == True:
try:
os.startfile("recog.py")
import time
time.sleep(6)
x = self.compare("security.jpg")
if x <= 30:
os.remove("pic1.jpg")
os.rename("security.jpg","pic1.jpg")
return True
else:
raise ValueError
except ValueError, e:
print(e)
sf=open('secure.txt','w')
sf.write("")
sf.close()
if os.path.exists("securitylog.jpg"):
from datetime import datetime, date, time
dt = datetime.today()
t=dt.strftime("%A, %d. %B %Y %H:%M %p")
t='{0:%H:%M }'.format(dt)
f='{0:%A}, {0:%d} of {0:%B}, {0:%Y}.'.format(dt)
timed=(("Date: ",f,"\nTime: ",t))
timed=''.join(timed)
sf=open('secure.txt','a')
sf.write(timed)
sf.close()
kl=Thread(target=self.say, args="You are not authorized to access this program.")
kl.start()
p = Wrong()

Solution

You should read and follow PEP8.
This means:

  • Put all imports at the top of the file.



  • Put a space around assignment operators.



  • Place a space after most commas.



  • Use descriptive names.



This is as it makes your code much easier to read.
We put spaces around words in English to increase readability,
we do it in programming languages to do the same.

You should:

-
Use with.

This makes sure the file is closed, even if the program errors. Say the user force quits the program, KeyboardInterrupt.

-
Don't use assert.

assert is for debugging, not for live code.
If I run your code with the -O flag, it removes all of these, and then your code is broken.

-
Allow more customizability.

Passing to functions a couple of file names is not hard.
What's more hard is when you decide to change pic1.jpg to image.jpg and also use pic1.jpeg.
This means you'll need to re-write your code to allow you to do this.

-
Don't have massive try blocks.

This can lead to masking of bugs.
This is as you may have two functions that raise say ValueErrors.
But you don't know which one raised ValueError, and now you're handling unknown states.

-
Again put all imports at the top of you files.

This allows me to know what you are importing as soon as I open your file.
This prevents confusion, like you did in main.py where you never import os, but you're using it.

-
Remove duplicated code.

You need to put duplicated code in a new function or re-arrange your current one to be able to merge the duplicated code.
Take password in main.py, you duplicated a large chunk of the function where you can join it together, or at least make a function for it.

The biggest changes I know how to make are to main.py. Other than the above, I changed your code to use less variables, and removed dead code.
Take:

dt = datetime.today()
t=dt.strftime("%A, %d. %B %Y %H:%M %p")
t='{0:%H:%M }'.format(dt)
f='{0:%A}, {0:%d} of {0:%B}, {0:%Y}.'.format(dt)
timed=(("Date: ",f,"\nTime: ",t))
timed=''.join(timed)


The first t is dead code, you instantly overwrite t to something else, so you can remove it.
After this you have the two timed variables, you can change this to a single str.format, Date: {}\nTime: {}.
From this you should notice you can merge all the str.formats into one, and end up with:

timed = 'Date: {0:%A}, {0:%d} of {0:%B}, {0:%Y}.\nTime: {0:%H:%M }'.format(datetime.today())


I'll only show the changes to main.py, as the other files didn't have as much to change:

from itertools import izip
import time
from datetime import datetime, date, time

from PIL import Image

import passw

def compare(self, picture1, picture2): 
    image1 = Image.open(picture1)
    image2 = Image.open(picture2).resize(image1.size)
    if image1.mode != image2.mode:
        raise ValueError("Different kinds of images.")
    if image1.size != image2.size:
        raise ValueError("Different sizes.")

    pairs = izip(image1.getdata(), image2.getdata())
    if len(image1.getbands()) == 1:
        dif = sum(abs(p1-p2) for p1, p2 in pairs)
    else:
        dif = sum(abs(c1-c2) for p1, p2 in pairs for c1, c2 in zip(p1,p2))

    ret = (dif / 255.0 * 100) / image1.size[0] * image1.size[1] * 3
    print ret
    return ret

def password(self):
    y = str(self.password_input.text)
    x = passw.verify(y)
    if x:
        try:
            os.startfile("recog.py")
            time.sleep(6)
            if self.compare("pic1.jpg", "security.jpg") <= 30:
                os.remove("pic1.jpg")
                os.rename("security.jpg", "pic1.jpg")
                return True
            else:
                raise ValueError
        except ValueError, e:
            print(e)

    # If not x or ValueError.
    with open('secure.txt', 'w') as sf:
        sf.write('')
    if os.path.exists("securitylog.jpg"):
        with open('secure.txt', 'a') as sf:
            sf.write('Date: {0:%A}, {0:%d} of {0:%B}, {0:%Y}.\nTime: {0:%H:%M }'
                     .format(datetime.today()))
        kl = Thread(target=self.say, args="You are not authorized to access this program.")
        kl.start()
        p = Wrong()
        p.open()
    else:
        os.rename("security.jpg", "securitylog.jpg")

Code Snippets

dt = datetime.today()
t=dt.strftime("%A, %d. %B %Y %H:%M %p")
t='{0:%H:%M }'.format(dt)
f='{0:%A}, {0:%d} of {0:%B}, {0:%Y}.'.format(dt)
timed=(("Date: ",f,"\nTime: ",t))
timed=''.join(timed)
timed = 'Date: {0:%A}, {0:%d} of {0:%B}, {0:%Y}.\nTime: {0:%H:%M }'.format(datetime.today())
from itertools import izip
import time
from datetime import datetime, date, time

from PIL import Image

import passw


def compare(self, picture1, picture2): 
    image1 = Image.open(picture1)
    image2 = Image.open(picture2).resize(image1.size)
    if image1.mode != image2.mode:
        raise ValueError("Different kinds of images.")
    if image1.size != image2.size:
        raise ValueError("Different sizes.")

    pairs = izip(image1.getdata(), image2.getdata())
    if len(image1.getbands()) == 1:
        dif = sum(abs(p1-p2) for p1, p2 in pairs)
    else:
        dif = sum(abs(c1-c2) for p1, p2 in pairs for c1, c2 in zip(p1,p2))

    ret = (dif / 255.0 * 100) / image1.size[0] * image1.size[1] * 3
    print ret
    return ret


def password(self):
    y = str(self.password_input.text)
    x = passw.verify(y)
    if x:
        try:
            os.startfile("recog.py")
            time.sleep(6)
            if self.compare("pic1.jpg", "security.jpg") <= 30:
                os.remove("pic1.jpg")
                os.rename("security.jpg", "pic1.jpg")
                return True
            else:
                raise ValueError
        except ValueError, e:
            print(e)

    # If not x or ValueError.
    with open('secure.txt', 'w') as sf:
        sf.write('')
    if os.path.exists("securitylog.jpg"):
        with open('secure.txt', 'a') as sf:
            sf.write('Date: {0:%A}, {0:%d} of {0:%B}, {0:%Y}.\nTime: {0:%H:%M }'
                     .format(datetime.today()))
        kl = Thread(target=self.say, args="You are not authorized to access this program.")
        kl.start()
        p = Wrong()
        p.open()
    else:
        os.rename("security.jpg", "securitylog.jpg")

Context

StackExchange Code Review Q#140604, answer score: 10

Revisions (0)

No revisions yet.