import tensorflow as tf
import sys
import numpy as np
from PIL import Image

import cv2
import os, os.path

# speicherorte fuer trainierten graph und labels in train.sh festlegen ##

# Disable tensorflow compilation warnings
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

image_path = sys.argv[1]
# angabe in console als argument nach dem aufruf 

##CROPPING

#multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('faces.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('eye.xml')

nfaces_detected = 0

# note the dependency on the format of the filename 
img = cv2.imread(image_path)
height = img.shape[0]
width = img.shape[1]
size = height * width
#???
#    if size > (500^2):
#        r = 500.0 / img.shape[1]
#        dim = (500, int(img.shape[0] * r))
#        img2 = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
#        img = img2

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #faces = face_cascade.detectMultiScale(gray, 1.3, 5)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(15, 15), flags = cv2.CASCADE_SCALE_IMAGE )

nface_within_pic = 0
for (x,y,w,h) in faces:
    face_with_eyes_detected = 0
    imgCrop = img[y:y+h,x:x+w]
        #cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
        #eyes = eye_cascade.detectMultiScale(roi_gray)
    eyes = face_cascade.detectMultiScale(roi_gray, scaleFactor=1.3, minNeighbors=3, minSize=(5, 5), flags = cv2.CASCADE_SCALE_IMAGE )
    eyesn = 0
    for (ex,ey,ew,eh) in eyes:
            #cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
        eyesn = eyesn +1
# allow detection if only one 1 eye for sideways face profile ?  
# No, always assume a frontal profile since that's the haar detection profile we chose above
#        if eyesn >= 1:
    if eyesn >= 1:
        face_with_eyes_detected = 1
        #cv2.imshow('img',imgCrop)
    if face_with_eyes_detected > 0:
        cv2.imwrite('face'+str(nface_within_pic)+'.jpg', imgCrop)
        print("Image has been processed and cropped")
        nface_within_pic += 1
        nfaces_detected += 1


##CROPPING ENDSL 


#CHOOSE BIGGEST FACE

filenames= ['face%d.jpg'%(i,) for i in range(nfaces_detected)]
sizes = [Image.open(f, 'r').size for f in filenames]
largest= max(sizes)
index= sizes.index(largest)
imagefile= filenames[index]
print(imagefile+ " is the largest face, so we will id it.")

#bilddatei readen
image_data = tf.gfile.FastGFile(imagefile, 'rb').read()

# holt labels aus file in array 
label_lines = [line.rstrip() for line 
                   in tf.gfile.GFile("tf_files/retrained_labels.txt")]
# !! labels befinden sich jeweils in eigenen lines -> keine aenderung in retrain.py noetig -> falsche darstellung im windows editor !!
				   
# graph einlesen, wurde in train.sh -> call retrain.py trainiert
with tf.gfile.FastGFile("tf_files/retrained_graph.pb", 'rb') as f:
 
    graph_def = tf.GraphDef()	## The graph-graph_def is a saved copy of a TensorFlow graph; objektinitialisierung
    graph_def.ParseFromString(f.read())	#Parse serialized protocol buffer data into variable
    _ = tf.import_graph_def(graph_def, name='')	# import a serialized TensorFlow GraphDef protocol buffer, extract objects in the GraphDef as tf.Tensor
	
	#https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/inception.py ; ab zeile 276

with tf.Session() as sess:

    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
	# return: Tensor("final_result:0", shape=(?, 4), dtype=float32); stringname definiert in retrain.py, zeile 1064 

    predictions = sess.run(softmax_tensor, \
             {'DecodeJpeg/contents:0': image_data})
    # gibt prediction values in array zuerueck:
	
    top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
	# sortierung; circle -> 0, plus -> 1, square -> 2, triangle -> 3; array return bsp [3 1 2 0] -> sortiert nach groesster uebereinstimmmung

	# output
    for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]
        print('%s (score = %.2f)' % (human_string, score))
import tensorflow as tf
import sys
import numpy as np
from PIL import Image

import cv2
import os, os.path

# speicherorte fuer trainierten graph und labels in train.sh festlegen ##

# Disable tensorflow compilation warnings
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

image_path = sys.argv[1]
# angabe in console als argument nach dem aufruf 

##CROPPING

#multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('faces.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('eye.xml')

nfaces_detected = 0

# note the dependency on the format of the filename 
img = cv2.imread(image_path)
height = img.shape[0]
width = img.shape[1]
size = height * width
#???
#    if size > (500^2):
#        r = 500.0 / img.shape[1]
#        dim = (500, int(img.shape[0] * r))
#        img2 = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
#        img = img2

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #faces = face_cascade.detectMultiScale(gray, 1.3, 5)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(15, 15), flags = cv2.CASCADE_SCALE_IMAGE )

nface_within_pic = 0
for (x,y,w,h) in faces:
    face_with_eyes_detected = 0
    imgCrop = img[y:y+h,x:x+w]
        #cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
        #eyes = eye_cascade.detectMultiScale(roi_gray)
    eyes = face_cascade.detectMultiScale(roi_gray, scaleFactor=1.3, minNeighbors=3, minSize=(5, 5), flags = cv2.CASCADE_SCALE_IMAGE )
    eyesn = 0
    for (ex,ey,ew,eh) in eyes:
            #cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
        eyesn = eyesn +1
# allow detection if only one 1 eye for sideways face profile ?  
# No, always assume a frontal profile since that's the haar detection profile we chose above
#        if eyesn >= 1:
    if eyesn >= 1:
        face_with_eyes_detected = 1
        #cv2.imshow('img',imgCrop)
    if face_with_eyes_detected > 0:
        cv2.imwrite('face'+str(nface_within_pic)+'.jpg', imgCrop)
        print("Image has been processed and cropped")
        nface_within_pic += 1
        nfaces_detected += 1


##CROPPING ENDSL 


#CHOOSE BIGGEST FACE

filenames= ['face%d.jpg'%(i,) for i in range(nfaces_detected)]
sizes = [Image.open(f, 'r').size for f in filenames]
largest= max(sizes)
index= sizes.index(largest)
imagefile= filenames[index]
print(imagefile+ " is the largest face, so we will id it.")

#bilddatei readen
image_data = tf.gfile.FastGFile(imagefile, 'rb').read()

# holt labels aus file in array 
label_lines = [line.rstrip() for line 
                   in tf.gfile.GFile("tf_files/retrained_labels.txt")]
# !! labels befinden sich jeweils in eigenen lines -> keine aenderung in retrain.py noetig -> falsche darstellung im windows editor !!
				   
# graph einlesen, wurde in train.sh -> call retrain.py trainiert
with tf.gfile.FastGFile("tf_files/retrained_graph.pb", 'rb') as f:
 
    graph_def = tf.GraphDef()	## The graph-graph_def is a saved copy of a TensorFlow graph; objektinitialisierung
    graph_def.ParseFromString(f.read())	#Parse serialized protocol buffer data into variable
    _ = tf.import_graph_def(graph_def, name='')	# import a serialized TensorFlow GraphDef protocol buffer, extract objects in the GraphDef as tf.Tensor
	
	#https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/inception.py ; ab zeile 276

with tf.Session() as sess:

    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
	# return: Tensor("final_result:0", shape=(?, 4), dtype=float32); stringname definiert in retrain.py, zeile 1064 

    predictions = sess.run(softmax_tensor, \
             {'DecodeJpeg/contents:0': image_data})
    # gibt prediction values in array zuerueck:
	
    top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
	# sortierung; circle -> 0, plus -> 1, square -> 2, triangle -> 3; array return bsp [3 1 2 0] -> sortiert nach groesster uebereinstimmmung

	# output
    for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]
        print('%s (score = %.2f)' % (human_string, score))
# speicherorte fuer trainierten graph und labels in train.sh festlegen ## # Disable tensorflow compilation warnings # angabe in console als argument nach dem aufruf ##CROPPING #multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml # note the dependency on the format of the filename #??? #    if size > (500^2): #        r = 500.0 / img.shape[1] #        dim = (500, int(img.shape[0] * r)) #        img2 = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) #        img = img2 #faces = face_cascade.detectMultiScale(gray, 1.3, 5) #cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #eyes = eye_cascade.detectMultiScale(roi_gray) #cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) # allow detection if only one 1 eye for sideways face profile ? # No, always assume a frontal profile since that's the haar detection profile we chose above #        if eyesn >= 1: #cv2.imshow('img',imgCrop) ##CROPPING ENDSL #CHOOSE BIGGEST FACE #bilddatei readen # holt labels aus file in array # !! labels befinden sich jeweils in eigenen lines -> keine aenderung in retrain.py noetig -> falsche darstellung im windows editor !! # graph einlesen, wurde in train.sh -> call retrain.py trainiert ## The graph-graph_def is a saved copy of a TensorFlow graph; objektinitialisierung #Parse serialized protocol buffer data into variable # import a serialized TensorFlow GraphDef protocol buffer, extract objects in the GraphDef as tf.Tensor #https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/inception.py ; ab zeile 276 # return: Tensor("final_result:0", shape=(?, 4), dtype=float32); stringname definiert in retrain.py, zeile 1064 # gibt prediction values in array zuerueck: # sortierung; circle -> 0, plus -> 1, square -> 2, triangle -> 3; array return bsp [3 1 2 0] -> sortiert nach groesster uebereinstimmmung # output