Пример #1
0
def image_search_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        #image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index_object_searching.html', has_result=True,
            result=[-1, 'Cannot open uploaded image.']
        )
    try:
        starttime = time.time()        
        image = exifutil.open_oriented_im(filename)        
        tmp_list = [filename]
        target_feature = image_feature_extract(tmp_list,1,1)
        
        
        L2_distance_feature = []
        res_images = []
        if app.is_gallery_feature_extract == True:
            logging.info('Begin to caculate L2_distance and sort.')
            for i in range(app.gallery_image_num):
                #caculate the L2 distance for f8 feature 
                tmp_distance = Euclidean_distance(app.gallery_features[i],target_feature[0])
                L2_distance_feature.append(tmp_distance)
            print "L2_distance_feature:",L2_distance_feature
            index = np.argsort(np.array(L2_distance_feature))                               
            for i in index:
                if L2_distance_feature[i] < app.threshold:
                    print 'Prepare output image, index: %d, distance:%d, name : %s \n'%(i,L2_distance_feature[i],app.gallery_image_name[i])
                    tmp_image = exifutil.open_oriented_im(app.gallery_image_name[i])
                    
                    res_images.append(embed_image_html(tmp_image))
                else:
                    break
            endtime = time.time()
            logging.info('Finish searching, output %d similar images.',len(res_images)) 
            return flask.render_template(
        'index_object_searching.html', has_result=True, result=[len(res_images),'%.3f' % (endtime - starttime)],result_images=res_images,imagesrc=embed_image_html(image) )

        else:
            endtime = time.time()
            return flask.render_template(
        'index_object_searching.html', has_result=True, result=[0,'%.3f' % (endtime - starttime)],result_images=res_images,imagesrc=embed_image_html(image) )
        
    except Exception as err:
            logging.info('Image searching error: %s', err)
            return flask.render_template(
            'index_object_searching.html', has_result=True,
            result=[-1, 'Something went wrong when searching image. '] )
Пример #2
0
def face_identify():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        imagepath = os.path.join(UPLOAD_FOLDER, filename_)
        #print("-------------------------------------------------------")
        #print(filename)
        imagefile.save(imagepath)
        logging.info('Saving to %s.', imagepath)
        image = exifutil.open_oriented_im(imagepath)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('index.html',
                                     has_result=False,
                                     result=(False,
                                             'Cannot open uploaded image.'))

    start_caffe(imagepath)

    #return flask.render_template('index.html', has_result=True, result=result, imagesrc=embed_image_html(image), predsrc=yolopred)
    return flask.render_template('index.html',
                                 has_result_face=True,
                                 imgsrc=embed_image_pred(image))
Пример #3
0
def enroll_upload():
  try:
    # We will save the file to disk for possible data collection.
    imagefile = flask.request.files['imagefile_enroll']
    filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
      werkzeug.secure_filename(imagefile.filename)
    filename = os.path.join(ENROLL_FOLDER, filename_)
    imagefile.save(filename)
    image = exifutil.open_oriented_im(filename)
    im = PIL.Image.fromarray(np.asarray(image * 255.).astype(np.uint8))
    im = im.resize( (384, 384), PIL.Image.ANTIALIAS )
    thumb_filename = filename #+ '_thumb.jpg'
    im.save(thumb_filename)
    #scp_command = 'scp %s [email protected]:%s' % (thumb_filename, ENROLL_FOLDER)
    #os.system(scp_command)
    logging.info('Saving to %s. done', thumb_filename)
    logging.info('%s done', scp_command)

  except Exception as err:
    logging.info('Uploaded image open error: %s', err)
    return flask.render_template(
      'index.html', has_result=True,
      result=(False, 'Cannot open uploaded image.')
    )

  result = app.clf.enroll_image(image, filename_)
  return flask.render_template('index.html', \
    has_result=True, result=result, imagesrc=embed_image_html(image))
Пример #4
0
def classify_upload_json():
    try:
        # We will save the file to disk for possible data collection.
        logging.info('In classify upload...')
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    result = app.clf.classify_image(image)
    
    #done with image file; no need to keep it around

    #os.remove(os.path.join(UPLOAD_FOLDER, filename))
    #logging.info('Deleted file with name, %s', (os.path.join(UPLOAD_FOLDER, filename)))

    return jsonify(result=result)
Пример #5
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('index.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open uploaded image.'))

    # result = app.clf.classify_image(image)

    app.clf.enqueue_image_files([imagefile])
    starttime = time.time()
    predicted = app.clf.feed_forward_batch(app.layer_names)
    endtime = time.time()
    timed = '%.3f' % (endtime - starttime)
    features = predicted[app.layer_names[0]]
    result = compare_to_base(features)

    return flask.render_template('index.html',
                                 has_result=True,
                                 result=(True, result),
                                 timed=timed,
                                 imagesrc=embed_image_html(image))
Пример #6
0
def classify_url():
    imageurl = flask.request.args.get('imageurl', '')
    try:
        if imageurl.startswith("/images/"):
            filename = os.path.dirname(os.path.abspath(__file__)) + imageurl
            logging.info('Image: %s', filename)
        else:
            filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
                        werkzeug.secure_filename(randomword(10))
            filename = os.path.join(UPLOAD_FOLDER, filename_)
            f = open(filename, "w")
            f.write(urllib.urlopen(imageurl).read())
            f.close()

        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('URL Image open error: %s', err)
        return flask.render_template(
            'error.html', error_msg='Cannot open image from URL.')

    logging.info('Image: %s', imageurl)
    return flask.render_template('results.html', classifiers=app.clf,
                                 imagesrc=embed_image_html(image),
                                 filename=filename)
Пример #7
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        # filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
        #     werkzeug.secure_filename(imagefile.filename)
        filename_ = str(uuid.uuid1()) + "_" + str(datetime.datetime.now()).replace(' ', '_') + "." + imagefile.filename.rsplit('.', 1)[1]
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        filenameMd5 = md5(filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True, has_images=False,
            result=(False, 'Cannot open uploaded image.')
        )

    result = app.clf.classify_image(image)

    try:
        dyCom = reClassify.DynamoCommunicator()
        s3 = reClassify.S3Wrapper()
        classes = []
        for item in result[2]:
            classes.append(item[0])

        if (not dyCom.isStored(filenameMd5)):

            s3.transfer.upload_file(filename, s3.BUCKET_NAME, s3.IMAGES_FOLDER + filename_, extra_args={'ACL': 'public-read'})
            dyCom.add_md5_and_image(filenameMd5,filename_)
            dyCom.add_image_to_classes(filename_, classes)
            dyCom.add_image_and_classes(filename_,classes, filenameMd5)


        images = dyCom.get_images(classes)

        imgIDs = []
        s3URL = "https://s3.amazonaws.com"
        s3URL = os.path.join(s3URL, s3.BUCKET_NAME, s3.IMAGES_FOLDER)

        for item in images:
	    samp = min(5,len(images[item]))
            for it in random.sample(images[item],samp):
                imgIDs.append(os.path.join(s3URL, str(it)))

    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('AWS Error: %s', err)
        return flask.render_template(
            'index.html', has_result=True, has_images=False,
            result=(False, "AWS Error" + err.message)
        )
    return flask.render_template(
        'index.html', has_result=True, result=result,
        imagesrc=embed_image_html(image), has_images=True, images=imgIDs
    )
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        path, extension = os.path.splitext(filename)
        if extension == '.png':
            im = Image.open(filename)
            filename = "%s.jpg" % path
            im.save(filename)

        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('index.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open uploaded image.'))

    names, probs, time_cost, accuracy = app.clf.classify_image(
        open(os.path.join(filename), "rb").read())
    return flask.render_template(
        'index.html',
        has_result=True,
        result=[True, zip(names, probs),
                '%.3f' % time_cost],
        imagesrc=embed_image_html(image))
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        path, extension = os.path.splitext(filename)
        if extension == '.png':
            im = Image.open(filename)
            filename = "%s.jpg" % path
            im.save(filename)

        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    names, probs, time_cost, accuracy = app.clf.classify_image(
        open(os.path.join(filename), "rb").read())
    return flask.render_template(
        'index.html', has_result=True, result=[True, zip(names, probs), '%.3f' % time_cost],
        imagesrc=embed_image_html(image)
    )
Пример #10
0
def classify_url():
    imageurl = flask.request.args.get('imageurl', '')
    try:
        string_buffer = StringIO.StringIO(urllib.urlopen(imageurl).read())
        image = caffe.io.load_image(string_buffer)

    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('URL Image open error: %s', err)
        return flask.render_template('index.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open image from URL.'))

    logging.info('Image: %s', imageurl)
    #result = app.clf.classify_image(image)

    #im_file2 = ('/home/ubuntu/jnb/py-faster-rcnn/data/demo/dog.jpg')
    image = Image.fromarray((255 * image).astype('uint8'))
    #cv2.imwrite('tmp.jpg',image)
    image.save(FORMAT_FILE, 'BMP')
    zfjnb(FORMAT_FILE)
    #logging.info('Saving to %s.', filename)
    image = exifutil.open_oriented_im('tmp.png')

    return flask.render_template(
        #'index.html', has_result=True, result=result, imagesrc=imageurl)
        'index.html',
        has_result=True,
        result=False,
        imagesrc=embed_image_html(image))
Пример #11
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    result = app.clf.classify_image(image)
    #print '----                         ..'
    #print result
    return flask.render_template(
        'index.html', has_result=True, result=result,
        imagesrc=embed_image_html(image)
    )
Пример #12
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('index2.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open uploaded image.'))

    result, image_show, seg, overlay, seg2, overlay2 = app.clf.classify_image(
        image)
    return flask.render_template('index2.html',
                                 has_result=True,
                                 result=result,
                                 imagesrc=embed_image_html(image_show),
                                 resultsrc=embed_image_html(seg),
                                 overlaysrc=embed_image_html(overlay),
                                 resultsrc2=embed_image_html(seg2),
                                 overlaysrc2=embed_image_html(overlay2))
Пример #13
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)
    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('example.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open uploaded image.'))

    rst_img, result_time = app.clf.search_image(image)
    img_tmp = ''''''
    for value in rst_img:
        img_tmp += '''<div class="col-xs-12 col-sm-9 col-md-1 clo-lg-3 marginDown" style="margin: 2% 2% 2% 0; "> ''' + '''<a href="#">''' + '''<img src=''' + url_for(
            'static', filename=value
        ) + ''' width="100" height="100"/>''' + '''</a>''' + '''</div>
    '''
    return flask.render_template('quer.html',
                                 has_result=True,
                                 result=(True, 'you did it.'),
                                 result_img=img_tmp,
                                 time=result_time)
Пример #14
0
def save_image(imagefile):
    filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
        werkzeug.secure_filename(imagefile.filename)
    filename = os.path.join(UPLOAD_FOLDER, filename_)
    imagefile.save(filename)
    logging.info('Saving to %s.', filename)
    image = exifutil.open_oriented_im(filename)
    return (filename, image)
Пример #15
0
def classify(net,labels,imagesFname):
    images = []
    for i in range(len(imagesFname)):
        images.append(exifutil.open_oriented_im(str(i)+'.jpg'))
    scores = net.predict(images, oversample=False)
    scoresLabels = [ labels[(-x).argsort()[:1][0] ] for x in scores ]
    output = zip( imagesFname, scoresLabels )
    return output
Пример #16
0
def classify(net, labels, imagesFname):
    images = []
    for i in range(len(imagesFname)):
        images.append(exifutil.open_oriented_im(str(i) + '.jpg'))
    scores = net.predict(images, oversample=False)
    scoresLabels = [labels[(-x).argsort()[:1][0]] for x in scores]
    output = zip(imagesFname, scoresLabels)
    return output
Пример #17
0
def embed_image_html(imagename):
    """Creates an image embedded in HTML base64 format."""
    image = exifutil.open_oriented_im(imagename)
    image_pil = Image.fromarray((255 * image).astype('uint8'))
    image_pil = image_pil.resize((256, 256))
    string_buf = StringIO.StringIO()
    image_pil.save(string_buf, format='png')
    data = string_buf.getvalue().encode('base64').replace('\n', '')
    return 'data:image/png;base64,' + data
Пример #18
0
def classify_upload():
    imagefile = request.files['imagefile']
    filename_ = werkzeug.secure_filename(imagefile.filename)
    filename = os.path.join(UPLOADS_FOLDER,filename_)
    imagefile.save(filename)
    image = exifutil.open_oriented_im(filename)
    result = classify_image(filename)
    print result
    imagesrc=embed_image_html(image)
    return render_template('index.html', has_result=True, result=result, imagesrc=imagesrc)
Пример #19
0
def show_team():
    photos = []
    
    filename1 = './templates/team-members-photo/wangbo.jpg'
    image1 = exifutil.open_oriented_im(filename1)
    member1=embed_image_html(image1)
    photos.append(member1)
        
    filename2 = './templates/team-members-photo/zdh.jpg'
    image2 = exifutil.open_oriented_im(filename2)
    member2=embed_image_html(image2)
    photos.append(member2)    
    
    filename3 = './templates/team-members-photo/zhuhao.jpg'
    image3 = exifutil.open_oriented_im(filename3)
    member3=embed_image_html(image3)
    photos.append(member3)
    
    return flask.render_template('index_team.html', has_result=False,imagesrc=photos)
Пример #20
0
def detect_and_render(img0):
    img = exifutil.open_oriented_im(StringIO.StringIO(img0))
    oh, ow = img.shape[:2]
    ret, time_cost = app.server.identify_receipt(img0)
    if oh > ow:
        img = imutils.resize(img, width=800)
        scale = 800.0 / ow
    else:
        img = imutils.resize(img, height=800)
        scale = 800.0 / oh
    # print(ret)l
    for r in ret["regions"]:
        reg = r["region"]
        reg = [
            int(reg[0] * scale),
            int(reg[1] * scale),
            int(reg[2] * scale),
            int(reg[3] * scale)
        ]
        if r["cls"] % 2 == 0:
            cv2.rectangle(img, (reg[0], reg[1]), (reg[2], reg[3]), (0, 0, 255),
                          1)
        else:
            cv2.rectangle(img, (reg[0], reg[1]), (reg[2], reg[3]), (255, 0, 0),
                          1)
    cv2_im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    pil_im = Image.fromarray(cv2_im)
    draw = ImageDraw.Draw(pil_im)
    font = ImageFont.truetype("data/simsun.ttc", 16, encoding="utf-8")
    for r in ret["regions"]:
        if len(r["result"]) == 0 or len(r["result"][0]) == 0:
            continue
        reg = r["region"]
        reg = [
            int(reg[0] * scale),
            int(reg[1] * scale),
            int(reg[2] * scale),
            int(reg[3] * scale)
        ]

        draw.text((reg[0], reg[3]),
                  "%s: %s" % (r["cls"], r["result"][0]), (0, 0, 255),
                  font=font)
    img = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)

    time_str = ['%.3f' % t for t in time_cost]

    type_info = json.dumps(ret.get("type", []), sort_keys=True)
    return flask.render_template('index.html',
                                 has_result=True,
                                 result=[
                                     True, 'time={}'.format(time_str),
                                     "class = {}".format(type_info)
                                 ],
                                 imagesrc=embed_image_html(img))
Пример #21
0
def classify_url():
        imageid = flask.request.args.get('imageid', '')
        imagename = ''
        if imageid=='1':
           imagename = File1
        elif imageid=='2':
           imagename = File2
        elif imageid=='3':
           imagename = File3
        elif imageid=='4':
           imagename = File4
        print imagename
        img = classify_file(imagename)
        img1 = exifutil.open_oriented_im(File1)
        img2 = exifutil.open_oriented_im(File2)
        img3 = exifutil.open_oriented_im(File3)
        img4 = exifutil.open_oriented_im(File4)
        return flask.render_template(
        'index.html', has_result=True, result='result',
        imagesrc=embed_image_html(img), imagesrc_1=embed_image_html(img1), imagesrc_2=embed_image_html(img2), imagesrc_3=embed_image_html(img3), imagesrc_4=embed_image_html(img4))
Пример #22
0
def detect_object():
    current_time = time.time()

    json_result = {
        "data": []
    }

    if flask.request.files['submitImageFile'].filename == '':
        return http_error_response("There is no image file.", 412)      

    try:
        imagefile = flask.request.files['submitImageFile']

        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
                    werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)

        imagefile.save(filename)
        logging.info('Saving to %s.', filename)

        # Convert wrong orientation of uploaded image
        im_arr = exifutil.open_oriented_im(filename)
        
        image_file_path =  filename.encode('utf-8')
        logging.info('image_file_path is %s.', image_file_path)

        # Detect the objects on uploaded image
        detected_result = app.detector.detect(image_file_path)

        if request.args.get('embed_image') == "true":
           detected_image = showAnnsBBox(im_arr, detected_result)
           json_result["data"].append(dict(detected_embed_image=embed_image_html(detected_image)))


        json_result["data"].append(dict(detected_results=detected_result))

        if os.path.exists(filename):
            os.remove(filename)
            logging.info('Uploaded image file is removed: %s', filename)

    except Exception as err:
        logging.info('Upload the image error: %s', err)

        if os.path.exists(filename):
            os.remove(filename)
            logging.info('Uploaded image file is removed: %s', filename)

        return http_error_response(err, 400)

    elapsed_time = time.time() - current_time
    json_result["data"].append(dict(elapsed_time=elapsed_time))
		
    return http_success_response("success", json_result)
Пример #23
0
def result():
    clfid = int(flask.request.args.get('c', 1)) - 1
    image = exifutil.open_oriented_im(flask.request.args.get('f'))
    result = app.clf[clfid].classify_image(image)
    data = { 'html':
             flask.render_template('_result.html', result=result,
                                   cnt=clfid+1),
             "_id": clfid+1
    }
    if len(result) > 3:
        data["timetaken"] = result[3]
    return flask.jsonify(data)
Пример #24
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        filename = flask.request.args["image"]
        logging.info("Saving to %s.", filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info("Uploaded image open error: %s", err)
        return flask.render_template("index.html", has_result=True, result=(False, "Cannot open uploaded image."))

    result = app.clf.classify_image(image)
    return flask.jsonify(result[2])
Пример #25
0
def myclassify_dog_upload():
    try:
        logging.info('in classify_upload')
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        logging.info('in classify_upload 1')
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        logging.info('in classify_upload 2')
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        logging.info('in classify_upload 3')
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'responseDogs.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    result = app.clf.classify_image(image)
    i = 0
    while i < len(result[1]):
         single_pred = result[1][i]
         if not(p.match(single_pred[0])):
           logging.info(single_pred[0] + " i=" + str(i))
           del result[1][i]
         else:
           #image support
           searchre = re.compile('.*'+single_pred[0].lower()+'.*',re.IGNORECASE)
           defkey = "borzoi"
           for key in dogs:
             if searchre.match(key):
               defkey = key
               break
           result[1][i] = [ single_pred[0], single_pred[1], dogs[defkey][2]]
           '''
           if single_pred[0].lower() in dogs:
             result[1][i] = [ single_pred[0], single_pred[1], dogs[single_pred[0].lower()][2]]
           else: 
             result[1][i] = [ single_pred[0], single_pred[1], dogs["borzoi"][2]]
           '''
           i = i + 1
 
    return flask.render_template(
        'responseDogs.html', has_result=True, result=result,
        imagesrc=embed_image_html(image)
    )
Пример #26
0
def classify_dir(imagedir,test):
  global f
  if test=='test':
    f=open('/opt/data/1000caffefileout-test.txt','a')
    for root, directories, filenames in os.walk(imagedir):
      for filename in filenames:
        if 'test' in root:
          if filename not in 'Thumbs.db':
            lfname =os.path.join(root,filename)
            catlog=root.split('/')[-3]
            cimage = exifutil.open_oriented_im(lfname)
            app.clf.classify_image(cimage,catlog,lfname)
    f.close()
  else:
    f=open('/opt/data/1000caffefileout.txt','a')
    for root, directories, filenames in os.walk(imagedir):
      for filename in filenames:
        if 'test' not in root:
          if filename not in 'Thumbs.db':
            lfname =os.path.join(root,filename)
            catlog=root.split('/')[-2]
            cimage = exifutil.open_oriented_im(lfname)
            app.clf.classify_image(cimage,catlog,lfname)
    f.close()
Пример #27
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files["imagefile"]
        filename_ = str(datetime.datetime.now()).replace(" ", "_") + werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info("Saving to %s.", filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info("Uploaded image open error: %s", err)
        return flask.render_template("index.html", has_result=True, result=(False, "Cannot open uploaded image."))

    result = app.clf.classify_image(image)
    return flask.render_template("classify.html", has_result=True, result=result, imagesrc=embed_image_html(image))
Пример #28
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        filename = flask.request.args['image']
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    result = app.clf.classify_image(image)
    return flask.jsonify(result[2])
Пример #29
0
def classifyy_upload():
    try:
        imagefile = request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOADS_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)
        
    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return render_template('index.html', has_result=True,result=(False, 'Cannot open uploaded image.'))
    
    logging.info('Image: %s', image_url)
    result = app.clf.classify_image(image)
    
    
Пример #30
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'error.html', error_msg='Cannot open uploaded image.')

    return flask.render_template('results.html', classifiers=app.clf,
                                 imagesrc=embed_image_html(image),
                                 filename=filename)
Пример #31
0
def classifyy_upload():
    try:
        imagefile = request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(
            ' ', '_') + werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOADS_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return render_template('index.html',
                               has_result=True,
                               result=(False, 'Cannot open uploaded image.'))

    logging.info('Image: %s', image_url)
    result = app.clf.classify_image(image)
Пример #32
0
def classify_upload():
    try:

        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        im = cv2.imread(filename)
        new = cv2.resize(im, (100, 46))

        try:
            wavfile = flask.request.files['wavefile']
            wavfilename_ = str(datetime.datetime.now()).replace(' ', '_') + \
                werkzeug.secure_filename(wavfile.filename)
            wavfilename = os.path.join(UPLOAD_FOLDER, wavfilename_)
            wavfile.save(wavfilename)
            imw = cv2.imread(wavfilename)
            neww = cv2.resize(imw, (90, 46))

            print("here")

        except Exception as err1:
            print("wave error: %s", err1)
            print(wavfilename)

        vis = np.concatenate((new, neww), axis=1)
        cv2.imwrite(filename, vis)

        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('index.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open uploaded image.'))

    result = app.clf.classify_image(image)
    return flask.render_template('index.html',
                                 has_result=True,
                                 result=result,
                                 imagesrc=embed_image_html(image))
Пример #33
0
def classify_upload():
    try:
        print "hello!", flask.request.files
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['filedata']
        print "imagefile", imagefile
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return jsonify('Cannot open uploaded image.')

    result = app.clf.classify_image(image)
    return jsonify(result)
Пример #34
0
def enroll_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files["imagefile_enroll"]
        filename_ = str(datetime.datetime.now()).replace(" ", "_") + werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(ENROLL_FOLDER, filename_)
        imagefile.save(filename)
        image = exifutil.open_oriented_im(filename)
        im = PIL.Image.fromarray(np.asarray(image * 255.0).astype(np.uint8))
        im = im.resize((256, 256), PIL.Image.ANTIALIAS)
        thumb_filename = filename + "_thumb.jpg"
        im.save(thumb_filename)
        logging.info("Saving to %s. done", thumb_filename)

    except Exception as err:
        logging.info("Uploaded image open error: %s", err)
        return flask.render_template("index.html", has_result=True, result=(False, "Cannot open uploaded image."))

    result = app.clf.enroll_image(image, filename_)
    return flask.render_template("index.html", has_result=True, result=result, imagesrc=embed_image_html(image))
Пример #35
0
def doframeclassify():
    print 'Starting ..'
    global net
    global labels
    global capframe
    global adblock
    global size
    global adchange
    while True:
        if capframe != None:
            cv2.imwrite('img' + '.jpg', capframe )
            images = [exifutil.open_oriented_im('img.jpg')]
            scores = net.predict(images, oversample=False)
            scoresLabels = [ labels[(-x).argsort()[:1][0] ] for x in scores ]  
            sstr = ' '.join(scoresLabels[0].split(' > ')[-2:]).replace('&','').split()
            img, title = getamazonres(sstr)
            print scoresLabels[0]
            createadchange(img,title,size)
            adchange = True
        capframe = None
Пример #36
0
def doframeclassify():
    print 'Starting ..'
    global net
    global labels
    global capframe
    global adblock
    global size
    global adchange
    while True:
        if capframe != None:
            cv2.imwrite('img' + '.jpg', capframe)
            images = [exifutil.open_oriented_im('img.jpg')]
            scores = net.predict(images, oversample=False)
            scoresLabels = [labels[(-x).argsort()[:1][0]] for x in scores]
            sstr = ' '.join(scoresLabels[0].split(' > ')[-2:]).replace(
                '&', '').split()
            img, title = getamazonres(sstr)
            print scoresLabels[0]
            createadchange(img, title, size)
            adchange = True
        capframe = None
Пример #37
0
def classify_upload():
    try:
        # Save file on disk.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        image = exifutil.open_oriented_im(filename)
    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return jsonify(success=0)

    result = app.clf.classify(image)
    success = result[0]
    if success:
        labels = result[1]
        scores = result[2]
        return jsonify(success=1, labels=labels, scores=scores)
    else:
        return jsonify(success=0)
def classify_url():
    imageurl = flask.request.args.get('imageurl', '')
    try:
        bytes = urllib2.urlopen(imageurl).read()
        string_buffer = StringIO.StringIO(bytes)
        image = exifutil.open_oriented_im(string_buffer)

    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('URL Image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True,
            result=(False, 'Cannot open image from URL.')
        )

    app.logger.info('Image: %s', imageurl)
    names, probs, time_cost, accuracy = app.clf.classify_image(bytes)
    return flask.render_template(
        'index.html', has_result=True, result=[True, zip(names, probs), '%.3f' % time_cost],
        imagesrc=embed_image_html(image)
    )
Пример #39
0
def classify_upload():
    try:
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template('clasification.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open uploaded image.'))
    # Basic clasification
    result = app.clf.classify_image(image)
    # Create list that would be embedable into html
    images_list = []
    # Run selectivesearch
    selectivesearch_result = app.clf._selective_search(image,
                                                       app.selectivesearch)
    selectivesearch_result, search_time = selectivesearch_result
    # Make output from selectivesearch embedable
    selectivesearch_result.append(image)
    embedable_images = embed_image_html(selectivesearch_result)
    x = 1
    # Fill the list with other images
    for image in embedable_images:
        images_list.append([str(x), image])
        x = x + 1
    return flask.render_template('clasification.html',
                                 images=images_list,
                                 result=result,
                                 search_time=search_time,
                                 has_result=True)
def classify_url():
    imageurl = flask.request.args.get('imageurl', '')
    try:
        bytes = urllib2.urlopen(imageurl).read()
        string_buffer = StringIO.StringIO(bytes)
        image = exifutil.open_oriented_im(string_buffer)

    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('URL Image open error: %s', err)
        return flask.render_template('index.html',
                                     has_result=True,
                                     result=(False,
                                             'Cannot open image from URL.'))

    app.logger.info('Image: %s', imageurl)
    names, probs, time_cost, accuracy = app.clf.classify_image(bytes)
    return flask.render_template(
        'index.html',
        has_result=True,
        result=[True, zip(names, probs),
                '%.3f' % time_cost],
        imagesrc=embed_image_html(image))
Пример #41
0
def classify_url():
    if 'url' in flask.request.args:
        imageurl = flask.request.args.get('url', '')
        try:
            string_buffer = StringIO.StringIO(
                urllib.urlopen(imageurl).read())
            image = caffe.io.load_image(string_buffer)

        except Exception as err:
            # For any exception we encounter in reading the image, we will just
            # not continue.
            logging.info('URL Image open error: %s', err)
            return json.dumps({ 'accuracy': [], 'specificity': [] })

        logging.info('Image: %s', imageurl)
        result = app.clf.classify_image(image)
        accuracy = [{ 'label': label, 'score': score } for label, score in result[2]]
        return json.dumps({ 'image': embed_image_html(image), 'accuracy': accuracy, 'specificity': accuracy })
    else:
        try:
            # We will save the file to disk for possible data collection.
            imagefile = flask.request.files['file']
            filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
                werkzeug.secure_filename(imagefile.filename)
            filename = os.path.join(UPLOAD_FOLDER, filename_)
            imagefile.save(filename)
            logging.info('Saving to %s.', filename)
            image = exifutil.open_oriented_im(filename)

        except Exception as err:
            logging.info('Uploaded image open error: %s', err)
            return json.dumps({ 'accuracy': [], 'specificity': [] })

        result = app.clf.classify_image(image)
        accuracy = [{ 'label': label, 'score': score } for label, score in result[2]]
        return json.dumps({ 'image': embed_image_html(image), 'accuracy': accuracy, 'specificity': accuracy })
Пример #42
0
def classify_url():
    imageurl = flask.request.args.get('imageurl', '')
    try:
        # string_buffer = StringIO.StringIO(
        #     urllib.urlopen(imageurl).read())
        # image = caffe.io.load_image(string_buffer)
        if allowed_file(imageurl):
            filename_ = str(uuid.uuid1()) + "_" + str(datetime.datetime.now()).replace(' ', '_') + "." + imageurl.rsplit('.', 1)[1]
            filename = os.path.join(UPLOAD_FOLDER, filename_)
            urllib.urlretrieve(imageurl, filename) # Download the image
            filenameMd5 = md5(filename)
            image = exifutil.open_oriented_im(filename)


    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('URL Image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True, has_images=False,
            result=(False, "URL Image open error " + err.message)
        )

    logging.info('Image: %s', imageurl)
    result = app.clf.classify_image(image)

    try:
        dyCom = reClassify.DynamoCommunicator()
        s3 = reClassify.S3Wrapper()
        classes = []
        for item in result[2]:
            classes.append(item[0])

        if (not dyCom.isStored(filenameMd5)):

            s3.transfer.upload_file(filename, s3.BUCKET_NAME, s3.IMAGES_FOLDER + filename_, extra_args={'ACL': 'public-read'})
            dyCom.add_md5_and_image(filenameMd5,filename_)
            dyCom.add_image_to_classes(filename_, classes)
            dyCom.add_image_and_classes(filename_,classes, filenameMd5)


        images = dyCom.get_images(classes)

        imgIDs = []
        s3URL = "https://s3.amazonaws.com"
        s3URL = os.path.join(s3URL, s3.BUCKET_NAME, s3.IMAGES_FOLDER)

        for item in images:
	    samp = min(5,len(images[item]))
            for it in random.sample(images[item],samp):
                imgIDs.append(os.path.join(s3URL, str(it)))

    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('AWS Error: %s', err)
        return flask.render_template(
            'index.html', has_result=True, has_images=False,
            result=(False, "AWS Error" + err.message)
        )

    return flask.render_template(
        'index.html', has_result=True, result=result, imagesrc=imageurl, images=imgIDs, has_images=True)
Пример #43
0
def image_search_url():
    imageurl = flask.request.args.get('imageurl', '')
    try:
        # string_buffer = StringIO.StringIO(
        #    urllib.urlopen(imageurl).read())
        #image_filename = imageurl.split('/')[-1]  
        image_filename = str(datetime.datetime.now()).replace(' ', '_')+'.jpg'
        filename = os.path.join(UPLOAD_FOLDER, image_filename)
        data = urllib.urlopen(imageurl).read()  

        f = file(filename,"wb")  
        f.write(data)  
        f.close()  


        #image = caffe.io.load_image(string_buffer)
        #filename_ = str(datetime.datetime.now()).replace(' ', '_')+'.jpg'
        #filename = os.path.join(UPLOAD_FOLDER, filename_)
        #image.save(filename)
        #logging.info('Saving to %s.', filename)
    except Exception as err:
        # For any exception we encounter in reading the image, we will just
        # not continue.
        logging.info('URL Image open error: %s', err)
        return flask.render_template(
            'index_object_searching.html', has_result=True,
            result=[-1, 'Cannot open image from URL.']
        )

    logging.info('Image: %s', imageurl)
    
    try:
        starttime = time.time()
        
        image = exifutil.open_oriented_im(filename)
        
        tmp_list = [filename]
        target_feature = image_feature_extract(tmp_list,1,1)
        
        L2_distance_feature = []
        res_images = []
        if app.is_gallery_feature_extract == True:
            logging.info('Begin to caculate L2_distance and sort.')
            for i in range(app.gallery_image_num):
                #caculate the L2 distance for f8 feature 
                tmp_distance = Euclidean_distance(app.gallery_features[i],target_feature[0])
                L2_distance_feature.append(tmp_distance)
            print "L2_distance_feature:",L2_distance_feature
            index = np.argsort(np.array(L2_distance_feature))
            
            for i in index:
                if L2_distance_feature[i] < app.threshold:
                    tmp_image = exifutil.open_oriented_im(app.gallery_image_name[i])
                    print 'Prepare output image, index: %d, distance:%d, name : %s \n'%(i,L2_distance_feature[i],app.gallery_image_name[i])
                    res_images.append(embed_image_html(tmp_image))
                else:
                    break
            endtime = time.time()
            logging.info('Finish searching, output %d similar images.',len(res_images)) 
            return flask.render_template(
        'index_object_searching.html', has_result=True, result=[len(res_images),'%.3f' % (endtime - starttime)],result_images=res_images,imagesrc=embed_image_html(image) )

        else:
            endtime = time.time()
            return flask.render_template(
        'index_object_searching.html', has_result=True, result=[0,'%.3f' % (endtime - starttime)],result_images=res_images,imagesrc=embed_image_html(image) )
        
    except Exception as err:
            logging.info('Image searching error: %s', err)
            return flask.render_template(
            'index_object_searching.html', has_result=True,
            result=[-1, 'Something went wrong when searching image. '] )
Пример #44
0
def index():
    img1 = exifutil.open_oriented_im(File1)
    img2 = exifutil.open_oriented_im(File2)
    img3 = exifutil.open_oriented_im(File3)
    img4 = exifutil.open_oriented_im(File4)
    return flask.render_template('index.html', has_result=False, imagesrc_1=embed_image_html(img1), imagesrc_2=embed_image_html(img2), imagesrc_3=embed_image_html(img3), imagesrc_4=embed_image_html(img4))
Пример #45
0
def classify_upload():
    try:
        cwd = os.getcwd()
        print cwd
        # We will save the file to disk for possible data collection.
        imagefile = flask.request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + werkzeug.secure_filename(imagefile.filename)
        filename_ = str(filename_).replace(':', '_')
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = cv2.imread(filename)
        r_img = cv2.cvtColor(image,cv2.COLOR_RGB2BGR)
        gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
        ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
        #kernel = np.ones((5,5),np.uint8)

        #opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
        #sure_bg = cv2.erode(opening,kernel,iterations=3)
        #sure_bg = cv2.erode(opening,kernel,iterations=3)

        criteria = np.uint8(thresh)
        height,width = criteria.shape[:2]
        blank_image = np.zeros((height,width), np.uint8)
        im2, contours, hierarchy = cv2.findContours(criteria,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        #cv2.fillPoly(blank_image, pts =[contours], color=(255,255,255))
        cv2.drawContours(blank_image, contours, -1, (255), cv2.FILLED)
        #cv2.imshow('image',blank_image)
        #cv2.waitKey(0)
       

        D = ndimage.distance_transform_edt(blank_image)
        localMax = peak_local_max(D, indices=False, min_distance=10,labels=blank_image)
 
# perform a connected component analysis on the local peaks,
# using 8-connectivity, then appy the Watershed algorithm
        markers = ndimage.label(localMax, structure=np.ones((3, 3)))[0]
        labels = watershed(-D, markers, mask=blank_image)
        print("[INFO] {} unique segments found".format(len(np.unique(labels)) - 1))
# loop over the unique labels returned by the Watershed
# algorithm
        c_img = image.copy()
        segment_id = 0
        for label in np.unique(labels):
	# if the label is zero, we are examining the 'background'
	# so simply ignore it
	     if label == 0:
		continue
 
	# otherwise, allocate memory for the label region and draw
	# it on the mask
	     mask = np.zeros(gray.shape, dtype="uint8")
	     mask[labels == label] = 255
 
	# detect contours in the mask and grab the largest one
	     cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
	     cv2.CHAIN_APPROX_SIMPLE)[-2]
	     c = max(cnts, key=cv2.contourArea)
             x, y, w, h = cv2.boundingRect(c)
             x = x-20
             y = y-20
             w = w+40
             h = h+40
             c_imag = c_img.copy() 
             roi = c_imag[y:y+h, x:x+w,:]
             if len(roi):
             	result = app.clf.classify_image(roi.copy())
             	#cv2.rectangle(image, (x, y), (x+w, y+h), (255),1)
             	time = str(datetime.datetime.now()).replace(' ', '_')
                time = str(time).replace(':', '_')
             	if result[1]=='lenfosit':
                 	cv2.rectangle(image, (x, y), (x+w, y+h), (0,0,0),2)
                        cv2.imwrite(UPLOAD_FOLDER_lenfosit+'lenfosit_' +time +str(segment_id)+'.jpg', roi)
             	elif result[1]=='eritrosit':
                 	cv2.rectangle(image, (x, y), (x+w, y+h), (255,0,0),2)
                        cv2.imwrite(UPLOAD_FOLDER_eritrosit+'eritrosit_' +time+str(segment_id)+'.jpg', roi)
             	elif result[1]=='monosit':
                 	cv2.rectangle(image, (x, y), (x+w, y+h), (0,255,0),2)
                        cv2.imwrite(UPLOAD_FOLDER_monosit +'monosit_'+time+str(segment_id)+'.jpg', roi)
             	elif result[1]=='notrofil':
                 	cv2.rectangle(image, (x, y), (x+w, y+h), (0,0,255),2)
                        cv2.imwrite(UPLOAD_FOLDER_notrofil +'notrofil_'+time+str(segment_id)+'.jpg', roi)
             	elif result[1]=='trombosit':
                 	cv2.rectangle(image, (x, y), (x+w, y+h), (203,102,255),2)
                        cv2.imwrite(UPLOAD_FOLDER_trombosit +'trombosit_'+time+str(segment_id)+'.jpg', roi)
	# draw a circle enclosing the object
	     #((x, y), r) = cv2.minEnclosingCircle(c)
	     #cv2.circle(image, (int(x), int(y)), int(r), (0, 255, 0), 2)
	     #cv2.putText(image, "#{}".format(label), (int(x) - 10, int(y)),
             #cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
                segment_id = segment_id +1
        cv2.imwrite(filename+'_AI', image)
        cv2.imwrite(filename, c_img)
        img = exifutil.open_oriented_im(filename+'_AI')


    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'index.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    #
    img1 = exifutil.open_oriented_im(File1)
    img2 = exifutil.open_oriented_im(File2)
    img3 = exifutil.open_oriented_im(File3)
    img4 = exifutil.open_oriented_im(File4)
    return flask.render_template('index.html', has_result=True, result=result, imagesrc=embed_image_html(img),imagesrc_1=embed_image_html(img1), imagesrc_2=embed_image_html(img2), imagesrc_3=embed_image_html(img3), imagesrc_4=embed_image_html(img4))
Пример #46
0
 def __init__(self):
     self.clf = ImagenetClassifier(**ImagenetClassifier.default_args)
     self.clf.net.forward()
     print("started caffe\n")
     image_file = "/crankshaw-local/caffe/examples/images/cat.jpg"
     self.test_image = exifutil.open_oriented_im(image_file)
Пример #47
0

caffe.set_mode_cpu()
#caffe.set_device(int(sys.argv[1]))
net = caffe.Classifier( model_def_file, pretrained_model_file,\
                        image_dims=(image_dim, image_dim), raw_scale=raw_scale,\
                        mean=np.load(mean_file).mean(1).mean(1), channel_swap=(2, 1, 0))
net.forward()

images=[]
imageFname = []
files = [ x.strip() for x in open( sys.argv[1] ).readlines() ]
#outpath = sys.argv[2] + '_' + 'output_shoess.tsv'                                                                                                                                                       
for img in files:
    try:
        images.append(exifutil.open_oriented_im(img))
        imageFname.append(img)
    except:
        print img
        continue
    if len(images) == 1 and len(imageFname) == 1:
        starttime = time.time()
        scores = net.predict(images, oversample=False)
        endtime = time.time()
        """
        x = net.blobs['fc7'].data
        filname = os.path.basename(imageFname[0]).split('.')[0]
        destname = '/home/indix/gps/cnnencodings/' + filname
        print filname
        np.save(destname,x)
        """
Пример #48
0
def classify_upload():
    """
    Predict the content of an image given from the local computer
    and show the image detection template.
    """
    model = request.form['model']
    solvermode = request.form['solvermode']
    try:
        # We will save the file to disk for possible data collection.
        imagefile = request.files['imagefile']
        filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
            werkzeug.secure_filename(imagefile.filename)
        filename = os.path.join(UPLOAD_FOLDER, filename_)
        imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        image = exifutil.open_oriented_im(filename)

    except Exception as err:
        logging.info('Uploaded image open error: %s', err)
        return flask.render_template(
            'image_detection.html', has_result=True,
            result=(False, 'Cannot open uploaded image.')
        )

    if (model == "cifar10quick"):
        convert_prototxt.PrototxtConverter(model, solvermode)
        starttime = time.time()
        classifier = classify.Classifier(solvermode)
        result = \
            classifier.classify_image(
                (os.environ['CAFFE_ROOT']) +
                '/examples/cifar10/cifar10_quick.prototxt',
                (os.environ['CAFFE_ROOT']) +
                '/examples/cifar10/cifar10_quick_iter_5000.caffemodel',
                (os.environ['CAFFE_ROOT'])+"/examples/cifar10/mean.npy",
                filename,
                (os.environ['CAFFE_ROOT'])+"/data/cifar10/batches.meta.txt",
                False)
        endtime = time.time()
        totaltime = round(endtime - starttime, 4)
    if (model == "cifar10full"):
        convert_prototxt.PrototxtConverter(model, solvermode)
        starttime = time.time()
        classifier = classify.Classifier(solvermode)
        result = \
            classifier.classify_image(
                (os.environ['CAFFE_ROOT']) +
                "/examples/cifar10/cifar10_full.prototxt",
                (os.environ['CAFFE_ROOT']) +
                "/examples/cifar10/cifar10_full_iter_70000.caffemodel",
                (os.environ['CAFFE_ROOT'])+"/examples/cifar10/mean.npy",
                filename,
                (os.environ['CAFFE_ROOT'])+"/data/cifar10/batches.meta.txt",
                False)
        endtime = time.time()
        totaltime = round(endtime - starttime, 4)
    if (model == "mnist"):
        convert_prototxt.PrototxtConverter(model, solvermode)
        starttime = time.time()
        classifier = classify.Classifier(solvermode)
        result = \
            classifier.classify_image(
                (os.environ['CAFFE_ROOT'])+'/examples/mnist/lenet.prototxt',
                (os.environ['CAFFE_ROOT']) +
                '/examples/mnist/lenet_iter_10000.caffemodel',
                None, filename, None, True)
        endtime = time.time()
        totaltime = round(endtime - starttime, 4)
    return flask.render_template('image_detection.html', has_result=True,
                                 result=result,
                                 imagesrc=embed_image_html(image),
                                 totaltime=totaltime)
Пример #49
0
def classify(filename):
    image = exifutil.open_oriented_im(filename)
    result = clf.classify_image(image)
    return result
Пример #50
0
Result = namedtuple('Result', 'OK maximally_accurate maximally_specific computation_time')

r_server = redis.StrictRedis(args.server, args.port)
r_server.config_set('notify-keyspace-events', 'Kh')

while True:
    task = Task(*r_server.brpop(args.queue))
    specs = Specs(**pickle.loads(task.value))
    logging.info(specs)
    result_key = 'prediction:{}:{}'.format(specs.user, specs.path)

    try:
        URL = not os.path.isfile(specs.path)
        if URL:
            response = requests.get(specs.path, timeout=10)
            string_buffer = StringIO.StringIO(response.content)
            image = caffe.io.load_image(string_buffer)
        else:
            image = exifutil.open_oriented_im(specs.path)

        result = Result(*model.classify_image(image))
        r_server.hmset(result_key, result._asdict())

        if URL:
            r_server.zadd('prediction:{}:category:{}'.format(specs.user, result.maximally_specific[0][0]),
                          result.maximally_specific[0][1], specs.path)

    except Exception as e:
        logging.error('Something went wrong when classifying the image: {}'.format(e))
        r_server.hmset(result_key, {'OK': 'False'})
Пример #51
0
def load():
    #f=request.files['imagefile']
    imagefile = request.files['imagefile']
    filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
        werkzeug.secure_filename(imagefile.filename)
    filename = os.path.join(UPLOAD_FOLDER, filename_)

    imagefile.save(filename)
    image = exifutil.open_oriented_im(filename)

    plt.rcParams['figure.figsize'] = (10, 10)  # large images
    plt.rcParams[
        'image.interpolation'] = 'nearest'  # don't interpolate: show square pixels
    plt.rcParams[
        'image.cmap'] = 'gray'  # use grayscale output rather than a (potentially misleading) color heatmap

    # The caffe module needs to be on the Python path;
    #  we'll add it here explicitly.

    caffe_root = '/home/speech/.local/install/caffe/'  # this file should be run from {caffe_root}/examples (otherwise change this line)
    sys.path.insert(0, caffe_root + 'python')

    # If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path.

    if os.path.isfile(caffe_root +
                      'models/placesCNN/places205CNN_iter_300000.caffemodel'):
        print('CaffeNet found')
    else:
        print('Downloading pre-trained CaffeNet model...')

    caffe.set_mode_cpu()

    model_def = caffe_root + 'models/placesCNN/places205CNN_deploy.prototxt'
    model_weights = caffe_root + 'models/placesCNN/places205CNN_iter_300000.caffemodel'

    net = caffe.Net(
        model_def,  # defines the structure of the model
        model_weights,  # contains the trained weights
        caffe.TEST)  # use test mode (e.g., don't perform dropout)

    # load the mean ImageNet image (as distributed with Caffe) for subtraction
    mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')
    mu = mu.mean(1).mean(
        1)  # average over pixels to obtain the mean (BGR) pixel values
    print('mean-subtracted values:', zip('BGR', mu))

    # create transformer for the input called 'data'
    transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})

    transformer.set_transpose(
        'data', (2, 0, 1))  # move image channels to outermost dimension
    transformer.set_mean('data',
                         mu)  # subtract the dataset-mean value in each channel
    transformer.set_raw_scale('data', 255)  # rescale from [0, 1] to [0, 255]
    transformer.set_channel_swap('data',
                                 (2, 1, 0))  # swap channels from RGB to BGR

    # set the size of the input (we can skip this if we're happy
    #  with the default; we can also change it later, e.g., for different batch sizes)
    net.blobs['data'].reshape(
        50,  # batch size
        3,  # 3-channel (BGR) images
        227,
        227)  # image size is 227x227

    img = caffe.io.load_image(filename)
    transformed_image = transformer.preprocess('data', img)
    plt.imshow(img)

    # copy the image data into the memory allocated for the net
    net.blobs['data'].data[...] = transformed_image

    ### perform classification
    output = net.forward()

    output_prob = output['prob'][
        0]  # the output probability vector for the first image in the batch

    print('predicted class is:', output_prob.argmax())

    # load ImageNet labels
    labels_file = caffe_root + 'data/place/categoryIndex_places205.csv'

    labels = np.loadtxt(labels_file, str, delimiter='\t')

    #thresh = raw_input("Enter input: ")
    thresh = 0.1
    top_inds = output_prob.argsort()[::-1]
    items = []
    for i in top_inds:
        a = Decimal(str(output_prob[i])).quantize(Decimal('.01'),
                                                  rounding=ROUND_HALF_EVEN)
        b = Decimal(str(thresh)).quantize(Decimal('.01'),
                                          rounding=ROUND_HALF_EVEN)
        if a.compare(b) >= 0:
            an_item = dict(a1=output_prob[i], a2=labels[i])
            items.append(an_item)

    options = {
        "model": "/home/speech/darkflow-master/cfg/tiny-yolo.cfg",
        "load": "/home/speech/darkflow-master/bin/tiny-yolo.weights",
        "threshold": 0.1
    }

    tfnet = TFNet(options)

    imgcv = cv2.imread(filename)
    result = tfnet.return_predict(imgcv)
    font = cv2.FONT_HERSHEY_SIMPLEX
    for r in result:
        cv2.rectangle(imgcv, (r['topleft']['x'], r['topleft']['y']),
                      (r['bottomright']['x'], r['bottomright']['y']),
                      (0, 255, 0), 1)
        cv2.putText(imgcv, r['label'],
                    (r['topleft']['x'], r['topleft']['y'] + 12), font, 0.47,
                    (255, 0, 0), 1)

    cv2.imwrite('outfile.jpg', imgcv)
    files = '/home/speech/.local/install/caffe/outfile.jpg'
    i = exifutil.open_oriented_im(files)

    return render_template('2.html',
                           imagesrc=embed_image_html(image),
                           items=items,
                           result=result,
                           isrc=embed_image_html(i))
Пример #52
0
    64,
    0,
    192,
    64,
    0,
    64,
    192,
    0,
    192,
    192,
    0,
]

net = caffe.Segmenter(MODEL_FILE, PRETRAINED, gpu=False)

input_image = 255 * exifutil.open_oriented_im(IMAGE_FILE)


# Mean values in BGR format
mean_vec = np.array([103.939, 116.779, 123.68], dtype=np.float32)
reshaped_mean_vec = mean_vec.reshape(1, 1, 3)

# Rearrange channels to form BGR
im = input_image[:, :, ::-1]

# Subtract mean
im = im - reshaped_mean_vec

# Pad as necessary
cur_h, cur_w, cur_c = im.shape
pad_h = 500 - cur_h