Example #1
0
def image_batch(image_path):
    coder = ImageCoder()
    image_data = tf.gfile.FastGFile(image_path, 'rb').read()
    image = coder.decode_jpeg(image_data)
    crop = tf.image.resize_images(image, (227, 227))
    image_batch = tf.stack([crop])
    # print(image_batch)
    return image_batch
Example #2
0
def guessGender(file_name):  # pylint: disable=unused-argument
    #检测单张照片的性别
    with tf.Session() as sess:
        with tf.device(FLAGS.device_id):
            init = tf.global_variables_initializer()

            requested_step = FLAGS.requested_step if FLAGS.requested_step else None

            checkpoint_path = '%s' % (GENDER_MODEL_PATH)

            model_checkpoint_path, global_step = get_checkpoint(checkpoint_path, requested_step, FLAGS.checkpoint)
            saver = tf.train.Saver()
            saver.restore(sess, model_checkpoint_path)

            softmax_output = tf.nn.softmax(logits)

            coder = ImageCoder()

            try:
                best_choice = classify(sess, label_list, softmax_output, coder, images, file_name)
                # print(best_choice)
                return(best_choice)


            except Exception as e:
                print(e)
                print('Failed to run image %s ' % file)
Example #3
0
    def __init__(
            self,
            model_dir='/usr/src/app/deps/rude-carnie/inception_gender_checkpoint',
            model_type='inception',
            class_type='gender'):
        '''
        Just a wrapper around guess.py.
        '''
        self.model_dir = model_dir
        self.model_type = model_type
        self.class_type = class_type
        self.sess = tf.Session()
        model_fn = select_model(self.model_type)
        self.label_list = AGE_LIST if self.class_type == 'age' else GENDER_LIST
        nlabels = len(self.label_list)
        self.images = tf.placeholder(tf.string, [None])
        standardize = tf.map_fn(self.decode, self.images, dtype=tf.float32)
        logits = model_fn(nlabels, standardize, 1, False)
        init = tf.global_variables_initializer()

        requested_step = None  #FLAGS.requested_step if FLAGS.requested_step else None

        checkpoint_path = '%s' % (self.model_dir)
        model_checkpoint_path, global_step = get_checkpoint(
            checkpoint_path, requested_step, None)
        #FLAGS.checkpoint)

        saver = tf.train.Saver()
        saver.restore(self.sess, model_checkpoint_path)

        self.softmax_output = tf.nn.softmax(logits)

        self.coder = ImageCoder()
def guessGender(path):  # pylint: disable=unused-argument

    with tf.Session() as sess:

        # tf.reset_default_graph()
        label_list = GENDER_LIST
        nlabels = len(label_list)

        print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model(FLAGS.model_type)

        with tf.device(FLAGS.device_id):

            images = tf.placeholder(tf.float32,
                                    [None, RESIZE_FINAL, RESIZE_FINAL, 3])
            logits = model_fn(nlabels, images, 1, False)
            init = tf.global_variables_initializer()

            requested_step = FLAGS.requested_step if FLAGS.requested_step else None

            checkpoint_path = '%s' % (GENDER_MODEL_PATH)

            model_checkpoint_path, global_step = get_checkpoint(
                checkpoint_path, requested_step, FLAGS.checkpoint)
            saver = tf.train.Saver()
            saver.restore(sess, model_checkpoint_path)

            softmax_output = tf.nn.softmax(logits)

            coder = ImageCoder()
            files = deal_file.get_files(path)
            font = cv2.FONT_HERSHEY_SIMPLEX

            try:
                for f in files:
                    best_choice = classify(sess, label_list, softmax_output,
                                           coder, images, f)
                    # print(best_choice)
                    pic = cv2.imread(f)
                    fname = f[:-4] + '_test' + f[-4:]
                    cv2.putText(pic, best_choice[0], (5, 40), font, 1,
                                (100, 255, 50), 2, cv2.LINE_AA)
                    cv2.imwrite(fname, pic)
                    print(best_choice)

            except Exception as e:
                print(e)
                print('Failed to run image %s ' % file)
def guessGender(path):  # pylint: disable=unused-argument
# 检测文件夹中所有照片的性别

    with tf.Session() as sess:

        # tf.reset_default_graph()
        label_list = GENDER_LIST
        nlabels = len(label_list)

        print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model(FLAGS.model_type)

        with tf.device(FLAGS.device_id):

            images = tf.placeholder(tf.float32, [None, RESIZE_FINAL, RESIZE_FINAL, 3])
            logits = model_fn(nlabels, images, 1, False)
            init = tf.global_variables_initializer()

            requested_step = FLAGS.requested_step if FLAGS.requested_step else None

            checkpoint_path = '%s' % (GENDER_MODEL_PATH)

            model_checkpoint_path, global_step = get_checkpoint(checkpoint_path, requested_step, FLAGS.checkpoint)
            saver = tf.train.Saver()
            saver.restore(sess, model_checkpoint_path)

            softmax_output = tf.nn.softmax(logits)

            coder = ImageCoder()
            files = get_files(path)
            gender_dict = {}

            try:
                for f in files:
                    best_choice = classify(sess, label_list, softmax_output, coder, images, f)
                    # print(best_choice)
                    gender_dict[f[len(path) + 1:]] = best_choice
                    return(best_choice)


            except Exception as e:
                print(e)
                print('Failed to run image %s ' % file)
Example #6
0
def guessAge(image_file):

    #import!!!Fix the bug http://stackoverflow.com/questions/33765336/remove-nodes-from-graph-or-reset-entire-default-graph
    tf.reset_default_graph()
    with tf.Session() as sess:

        age_label_list = AGE_LIST
        agelabels = len(age_label_list)

        # print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model('inception')

        images = tf.placeholder(tf.float32,
                                [None, RESIZE_FINAL, RESIZE_FINAL, 3])
        logits_age = model_fn(agelabels, images, 1, False)
        init = tf.global_variables_initializer()

        requested_step = FLAGS.requested_step if FLAGS.requested_step else None

        checkpoint_path = '%s' % (AGE_MODEL_PATH)
        # update in 0.11 version

        model_checkpoint_path, global_step = get_checkpoint(
            checkpoint_path, requested_step, FLAGS.checkpoint)
    #print 'model_checkpoint_path is', model_checkpoint_path
    #print model_checkpoint_path
    saver = tf.train.Saver()
    if not saver.last_checkpoints:
        saver.restore(sess, model_checkpoint_path)

    softmax_output = tf.nn.softmax(logits_age)

    coder = ImageCoder()

    files = []

    # detect age
    best_choice = classify(sess, age_label_list, softmax_output, coder, images,
                           image_file)

    sess.close()
    return best_choice
Example #7
0
def main(argv=None):  # pylint: disable=unused-argument

    with tf.Session() as sess:

        label_list = AGE_LIST if FLAGS.class_type == 'age' else GENDER_LIST
        nlabels = len(label_list)

        print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model(FLAGS.model_type)

        images = tf.placeholder(tf.float32,
                                [None, RESIZE_FINAL, RESIZE_FINAL, 3])
        logits = model_fn(nlabels, images, 1, False)
        init = tf.initialize_all_variables()

        requested_step = FLAGS.requested_step if FLAGS.requested_step else None

        checkpoint_path = '%s' % (FLAGS.model_dir)

        model_checkpoint_path, global_step = get_checkpoint(
            checkpoint_path, requested_step, FLAGS.checkpoint)

        saver = tf.train.Saver()
        saver.restore(sess, model_checkpoint_path)

        softmax_output = tf.nn.softmax(logits)

        coder = ImageCoder()

        files = []

        if FLAGS.face_detection_model:
            print('Using face detector %s' % FLAGS.face_detection_model)
            face_detect = FaceDetector(FLAGS.face_detection_model)
            face_files, rectangles = face_detect.run(FLAGS.filename)
            files += face_files

        if len(files) == 0:
            files.append(FLAGS.filename)

        for f in files:
            classify(sess, label_list, softmax_output, coder, images, f)
Example #8
0
def guessGender(image_file):
    tf.reset_default_graph()
    with tf.Session() as sess:

        #sess = tf.Session()
        age_label_list = AGE_LIST
        gender_label_list = GENDER_LIST
        genderlabels = len(gender_label_list)

        # print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model('')

        with tf.device(FLAGS.device_id):

            images = tf.placeholder(tf.float32,
                                    [None, RESIZE_FINAL, RESIZE_FINAL, 3])
            logits_gender = model_fn(genderlabels, images, 1, False)
            init = tf.global_variables_initializer()

            requested_step = FLAGS.requested_step if FLAGS.requested_step else None

            checkpoint_path = '%s' % (GENDER_MODEL_PATH)

            model_checkpoint_path, global_step = get_checkpoint(
                checkpoint_path, requested_step, FLAGS.checkpoint)

            saver = tf.train.Saver()
            saver.restore(sess, model_checkpoint_path)

            softmax_output = tf.nn.softmax(logits_gender)

            coder = ImageCoder()

            files = []

            # detect gender
            #try:
            best_choice = classifyGender(sess, gender_label_list,
                                         softmax_output, coder, images,
                                         image_file)
            return best_choice
Example #9
0
def guessGender(image_file):
    with tf.Session() as sess:

        sess = tf.Session()
        age_label_list = AGE_LIST
        gender_label_list = GENDER_LIST
        genderlabels = len(gender_label_list)

        # print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model('inception')

        images = tf.placeholder(tf.float32,
                                [None, RESIZE_FINAL, RESIZE_FINAL, 3])
        logits_gender = model_fn(genderlabels, images, 1, False)
        init = tf.global_variables_initializer()

        requested_step = FLAGS.requested_step if FLAGS.requested_step else None

        checkpoint_path = '%s' % (FLAGS.model_dir)

        model_checkpoint_path, global_step = get_checkpoint(
            checkpoint_path, requested_step, FLAGS.checkpoint)

        saver = tf.train.Saver()
        saver.restore(sess, model_checkpoint_path)

        softmax_output = tf.nn.softmax(logits_gender)

        coder = ImageCoder()

        files = []

        # detect age
        try:
            best_choice = classify(sess, gender_label_list, softmax_output,
                                   coder, images, image_file)
            return best_choice
        except Exception as e:
            print(e)
            print('Failed to run image %s ' % image_file)
Example #10
0
def main(argv=None):  # pylint: disable=unused-argument


    with tf.Session() as sess:

        label_list = AGE_LIST if FLAGS.class_type == 'age' else GENDER_LIST
        nlabels = len(label_list)

        print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model(FLAGS.model_type)

        images = tf.placeholder(tf.float32, [None, RESIZE_FINAL, RESIZE_FINAL, 3])
        logits = model_fn(nlabels, images, 1, False)
        init = tf.global_variables_initializer()
            
        requested_step = FLAGS.requested_step if FLAGS.requested_step else None
        
        checkpoint_path = '%s' % (FLAGS.model_dir)

        model_checkpoint_path, global_step = get_checkpoint(checkpoint_path, requested_step, FLAGS.checkpoint)
            
        saver = tf.train.Saver()
        saver.restore(sess, model_checkpoint_path)
                        
        softmax_output = tf.nn.softmax(logits)

        coder = ImageCoder()

        files = []

        if FLAGS.face_detection_model:
            print('Using face detector %s' % FLAGS.face_detection_model)
            face_detect = FaceDetector(FLAGS.face_detection_model)
            face_files, rectangles = face_detect.run(FLAGS.filename)
            files += face_files

        # Support a batch mode if no face detection model
        if len(files) == 0:
            files.append(FLAGS.filename)
            # If it happens to be a list file, read the list and clobber the files
            if one_of(FLAGS.filename, ('csv', 'tsv', 'txt')):
                files = batchlist(FLAGS.filename)

        writer = None
        output = None
        if FLAGS.target:
            print('Creating output file %s' % FLAGS.target)
            output = open(FLAGS.target, 'w')
            writer = csv.writer(output)
            writer.writerow(('file', 'label', 'score'))


        for f in files:
            image_file = resolve_file(f)
            
            if image_file is None: continue

            try:
                best_choice = classify(sess, label_list, softmax_output, coder, images, image_file)
                if writer is not None:
                    writer.writerow((f, best_choice[0], '%.2f' % best_choice[1]))
            except Exception as e:
                print(e)
                print('Failed to run image %s ' % image_file)

        if output is not None:
            output.close()
Example #11
0
        crops.append(standardize_image(cropped))
        flipped = standardize_image(tf.image.flip_left_right(cropped))
        crops.append(standardize_image(flipped))

    image_batch = tf.stack(crops)
    return image_batch

def make_single_image_batch(image_path, coder):
    image_data = tf.gfile.FastGFile(image_path, 'rb').read()
    image = coder.decode_jpeg(image_data)
    crop = tf.image.resize_images(image, (227,227))
    image_batch = tf.stack([crop])
    return image_batch

with tf.Session() as sess:
    coder = ImageCoder()
    image_batch = make_multi_crop_batch(image_file, coder)
    image_batch = image_batch.eval()

configuration = skil_client.Configuration()
configuration.host = 'http://192.168.1.128:9008'
configuration.username = '******'
configuration.password = '******'

r = requests.post("http://192.168.1.128:9008/login", json={"userId": "admin", "password": "******"})
token = r.json()['token']

configuration.api_key['authorization'] = f'Bearer {token}'
api_instance = skil_client.DefaultApi(skil_client.ApiClient(configuration))

Example #12
0
def construct(filename,
              class_type,
              model_type,
              model_dir,
              checkpoint='checkpoint',
              device='/cpu:0',
              target=None,
              classes=None):  # pylint: disable=unused-argument
    # sys.stdout = os.devnull
    # sys.stderr = os.devnull
    files = []
    with tf.Graph().as_default():
        with tf.Session() as sess:
            #with tf.Session() as sess:
            #print('\n111111111111111\n')
            #tf.reset_default_graph()
            label_list = AGE_LIST if class_type == 'age' else GENDER_LIST
            nlabels = len(label_list)
            #print('\n222222222222222\n')
            #print('Executing on %s' % FLAGS.device_id)
            model_fn = select_model(model_type)

            with tf.device(device):
                # sys.stdout = sys.__stdout__
                # sys.stderr = sys.__stderr__
                images = tf.placeholder(tf.float32,
                                        [None, RESIZE_FINAL, RESIZE_FINAL, 3])
                logits = model_fn(nlabels, images, 1, False)
                init = tf.global_variables_initializer()
                #print('\n333333333333333\n')
                requested_step = None

                checkpoint_path = '%s' % (model_dir)

                model_checkpoint_path, global_step = get_checkpoint(
                    checkpoint_path, requested_step, checkpoint)
                #print("\nglobal_step=",global_step)
                saver = tf.train.Saver()
                #print('\n44444444444444444\n')
                #print("PATH=",model_checkpoint_path,'\n')
                saver.restore(sess, model_checkpoint_path)
                #print('\n55555555555555555\n')
                softmax_output = tf.nn.softmax(logits)

                coder = ImageCoder()

                # Support a batch mode if no face detection model
                if len(files) == 0:
                    files.append(filename)
                    # If it happens to be a list file, read the list and clobber the files
                    if one_of(filename, ('csv', 'tsv', 'txt')):
                        files = batchlist(filename)

                for it, f in enumerate(files):
                    image_file = resolve_file(f)

                    if image_file is None: continue

                    try:
                        best_choice = classify(sess, label_list,
                                               softmax_output, coder, images,
                                               image_file)
                        #results[it][0]=f
                        #print('f=%s\nresult='%f,results)
                        print("\nClass_type=", class_type)
                        if class_type == 'age':
                            #print("\n%s\n"%it)
                            classes[it].age = best_choice[0]
                            # print(best_choice[0],'\n')
                            # print(results,'\n')
                            target.writerow(
                                (f, classes[it].gender, classes[it].age,
                                 '%.2f' % best_choice[1]))
                        if class_type == 'gender':
                            #print("\n222222222\n")
                            classes[it].name = f
                            classes[it].gender = best_choice[0]
                    except Exception as e:
                        print(e)
                        print('Failed to run image %s ' % image_file)
                    it += 1
                #if output is not None:
                #    output.close()
                # print(results)
                sess.close()
Example #13
0
def main(argv=None):  # pylint: disable=unused-argument

    # FIXME: Test by putting in multiple files in here.
    # files = []
    files = load_imgs(
        '/Users/parimarjann/projects/face_recognizer/data/vgg_face_dataset/dataset_images'
    )
    random.seed(1234)
    files = random.sample(files, 100)
    print('single look: ', FLAGS.single_look)

    if FLAGS.face_detection_model:
        print('Using face detector (%s) %s' %
              (FLAGS.face_detection_type, FLAGS.face_detection_model))
        face_detect = face_detection_model(FLAGS.face_detection_type,
                                           FLAGS.face_detection_model)
        face_files, rectangles = face_detect.run(FLAGS.filename)
        print(face_files)
        files += face_files

    with tf.Session() as sess:

        #tf.reset_default_graph()
        label_list = AGE_LIST if FLAGS.class_type == 'age' else GENDER_LIST
        nlabels = len(label_list)

        print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model(FLAGS.model_type)

        with tf.device(FLAGS.device_id):

            images = tf.placeholder(tf.float32,
                                    [None, RESIZE_FINAL, RESIZE_FINAL, 3])
            logits = model_fn(nlabels, images, 1, False)
            init = tf.global_variables_initializer()

            requested_step = FLAGS.requested_step if FLAGS.requested_step else None

            checkpoint_path = '%s' % (FLAGS.model_dir)

            model_checkpoint_path, global_step = get_checkpoint(
                checkpoint_path, requested_step, FLAGS.checkpoint)

            saver = tf.train.Saver()
            saver.restore(sess, model_checkpoint_path)

            softmax_output = tf.nn.softmax(logits)

            coder = ImageCoder()
            # Support a batch mode if no face detection model
            if len(files) == 0:
                files.append(FLAGS.filename)
                # If it happens to be a list file, read the list and clobber the files
                if one_of(FLAGS.filename, ('csv', 'tsv', 'txt')):
                    files = batchlist(FLAGS.filename)

            writer = None
            output = None
            if FLAGS.target:
                print('Creating output file %s' % FLAGS.target)
                output = open(FLAGS.target, 'w')
                writer = csv.writer(output)
                writer.writerow(('file', 'label', 'score'))

            for f in files:
                image_file = resolve_file(f)
                image_data = cv2.imread(image_file)
                image_data = cv2.cvtColor(image_data, cv2.COLOR_RGB2BGR)
                image_data = cv2.imencode('.jpeg', image_data)[1].tostring()

                if image_file is None:
                    continue

                try:
                    best_choice = classify(sess, label_list, softmax_output,
                                           coder, images, image_data)
                    # if writer is not None:
                    # writer.writerow((f, best_choice[0], '%.2f' % best_choice[1]))
                    print(f)
                    print(best_choice)
                except Exception as e:
                    print('exception!')
                    print(e)
                    print('Failed to run image %s ' % image_file)

            if output is not None:
                output.close()
Example #14
0
AGE_LIST = [
    '(0, 2)', '(4, 6)', '(8, 12)', '(15, 20)', '(25, 32)', '(38, 43)',
    '(48, 53)', '(60, 100)'
]

with tf.Session() as sess:
    nlabels = len(AGE_LIST)
    from model import inception_v3
    images = tf.placeholder(tf.float32, [None, 227, 227, 3])
    logits = inception_v3(nlabels, images, 1, False)
    init = tf.global_variables_initializer()

    saver = tf.train.Saver()
    saver.restore(sess, 'D:\\model\\age\\inception\\checkpoint-14999')
    softmax_output = tf.nn.softmax(logits)
    coder = ImageCoder()

    image_data = tf.gfile.FastGFile("test1.jpg", 'rb').read()
    image = coder.decode_jpeg(image_data)
    crop = tf.image.resize_images(image, (RESIZE_FINAL, RESIZE_FINAL))
    image_batch = tf.stack([crop])

    batch_results = sess.run(softmax_output,
                             feed_dict={images: image_batch.eval()})
    output = batch_results[0]
    batch_sz = batch_results.shape[0]
    for i in range(1, batch_sz):
        output = output + batch_results[i]

    output /= batch_sz
    best = np.argmax(output)
Example #15
0
def construct(filename,
              class_type,
              model_type,
              model_dir,
              checkpoint='checkpoint',
              device='/cpu:0',
              target=None):  # pylint: disable=unused-argument

    files = []
    with tf.Graph().as_default():
        sess = tf.InteractiveSession()
        #with tf.Session() as sess:
        #print('\n111111111111111\n')
        #tf.reset_default_graph()
        label_list = AGE_LIST if class_type == 'age' else GENDER_LIST
        nlabels = len(label_list)
        #print('\n222222222222222\n')
        #print('Executing on %s' % FLAGS.device_id)
        model_fn = select_model(model_type)

        with tf.device(device):

            images = tf.placeholder(tf.float32,
                                    [None, RESIZE_FINAL, RESIZE_FINAL, 3])
            logits = model_fn(nlabels, images, 1, False)
            init = tf.global_variables_initializer()
            #print('\n333333333333333\n')
            requested_step = None

            checkpoint_path = '%s' % (model_dir)

            model_checkpoint_path, global_step = get_checkpoint(
                checkpoint_path, requested_step, checkpoint)
            #print("\nglobal_step=",global_step)
            saver = tf.train.Saver()
            #print('\n44444444444444444\n')
            #print("PATH=",model_checkpoint_path,'\n')
            saver.restore(sess, model_checkpoint_path)
            #print('\n55555555555555555\n')
            softmax_output = tf.nn.softmax(logits)

            coder = ImageCoder()

            # Support a batch mode if no face detection model
            if len(files) == 0:
                files.append(filename)
                # If it happens to be a list file, read the list and clobber the files
                if one_of(filename, ('csv', 'tsv', 'txt')):
                    files = batchlist(filename)

            writer = None
            output = None
            if target:
                #print('Creating output file %s' % FLAGS.target)
                output = open(target, 'w')
                writer = csv.writer(output)
                writer.writerow(('file', 'label', 'score'))

            for f in files:
                image_file = resolve_file(f)

                if image_file is None: continue

                try:
                    best_choice = classify(sess, label_list, softmax_output,
                                           coder, images, image_file)
                    if writer is not None:
                        writer.writerow(
                            (f, best_choice[0], '%.2f' % best_choice[1]))
                except Exception as e:
                    print(e)
                    print('Failed to run image %s ' % image_file)

            if output is not None:
                output.close()
            sess.close()