예제 #1
0
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('file',
                           type=werkzeug.datastructures.FileStorage,
                           location='files')

        args = parse.parse_args()
        imageFile = args['file']
        if imageFile == None:
            return {'Error': "please specify image file"}
        fh, tmp_image_file = tempfile.mkstemp(suffix='_up.jpg',
                                              dir='files',
                                              text=False)
        imageFile.save(tmp_image_file)
        img_path = tmp_image_file
        model = ResNet50(weights='imagenet')
        img = image.load_img(img_path, target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)

        preds = model.predict(x)
        # decode the results into a list of tuples (class, description, probability)
        # (one such list for each sample in the batch)
        print('Predicted:', decode_predictions(preds, top=3)[0])
        return {'Predicted': decode_predictions(preds, top=3)[0][0][1]}
예제 #2
0
def imageprocess(request):
    form = ImageUploadForm(request.POST, request.FILES)
    if form.is_valid():
        handle_uploaded_file(request.FILES['image'])

        model = ResNet50(weights='imagenet')
        img_path = 'img.jpg'
        #loading the image
        img = image.load_img(img_path, target_size=(224, 224))
        #convert image to array , 2D
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        #preprocess data and get ready for prediction
        x = preprocess_input(x)
        #predicting the values
        preds = model.predict(x)
        #predicting the animal
        print('Predicted animal :', decode_predictions(preds, top=3)[0])

        html = decode_predictions(preds, top=3)[0]
        res = []
        for e in html:
            res.append((e[1], np.round(e[2] * 100, 2)))
        return render(request, 'result.html', {'res': res})

    return render(request, 'result.html')
예제 #3
0
    def exposed_resnet50(self, img_path):
        model = ResNet50(weights='imagenet')
        img = image.load_img(img_path, target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)

        preds = model.predict(x)
        # decode the results into a list of tuples (class, description, probability)
        # (one such list for each sample in the batch)
        print('Predicted:', decode_predictions(preds, top=3)[0])
        return {'Predicted': decode_predictions(preds, top=3)[0][0][1]}
예제 #4
0
def print_time():
    timer = time.time()
    batch = form_batch()
    print("form_batch(): %s ms" % ((time.time() - timer) * 1000))

    timer = time.time()
    # preds = model.predict_on_batch(batch)
    preds = model.predict(batch)
    print("predict(): %s ms" % ((time.time() - timer) * 1000))

    timer = time.time()
    decode_predictions(preds)
    print("decode_predictions(): %s ms \n" % ((time.time() - timer) * 1000))
예제 #5
0
def print_time():
    timer = time.time()
    batch = form_batch()
    print("form_batch(): %s ms" % ((time.time() - timer) * 1000))

    timer = time.time()
    labeling = infer(batch)
    # preds = labeling['probs'].numpy()
    # preds = model.predict(batch)
    print("predict(): %s ms" % ((time.time() - timer) * 1000))

    timer = time.time()
    preds = labeling['predictions'].numpy()
    decode_predictions(preds)
    print("decode_predictions(): %s ms \n" % ((time.time() - timer) * 1000))
예제 #6
0
async def classify(request):
    cam_id = request.match_info['stream']
    cams = await get_cams(args.nvr_token)
    cam_info = [cam for cam in cams if str(cam['id']) == cam_id]
    if not cam_info:
        raise web.HTTPNotFound(text='No rtsp source related to this url')
    cam_info = cam_info[0]
    play_from = cam_info['rtsp']

    if cam_id not in cam_rtsp:
        cam_rtsp[cam_id] = {}
        cam_rtsp[cam_id]['client'] = rtsp.Client(play_from)
        cam_rtsp[cam_id]['time'] = time()

    if (time() - cam_rtsp[cam_id]['time']) > 120:
        cam_rtsp[cam_id]['client'].close()
        cam_rtsp[cam_id]['client'] = rtsp.Client(play_from)
        cam_rtsp[cam_id]['time'] = time()

    im = cam_rtsp[cam_id]['client'].read()
    if im:
        im = im.resize((224, 224))
        x = image.img_to_array(im)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        preds = model.predict(x)
        text = str([i[1] for i in decode_predictions(preds, top=3)[0]])
    else:
        text = ''
    return web.Response(headers=cors_headers, text=text)
예제 #7
0
def show_upload(filename):
    debug = False
    # load image, resize, convert to numpy array
    img_path = app.config['UPLOADED_PHOTOS_DEST'] + '/' + filename
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = x[np.newaxis, ...]
    x = preprocess_input(x)
    # predict
    y_pred = model.predict(x)
    predictions = decode_predictions(y_pred, top=5)[0]
    url = photos.url(filename)
    # get mostly likely prediction
    indices = np.argmax(predictions, axis=0)
    max_index = indices[2]
    max_class = predictions[max_index][1]
    max_prob = "{:.1f}".format(100 * predictions[max_index][2])
    if debug:
        for i in range(len(predictions)):
            print("prediction {0}: {1}, {2}".format(i, predictions[i][1],
                                                    predictions[i][2]))
        print("indices: {0}".format(indices))
        print("max_index: {0}, max_class: {1}, max_prob: {2}".format(
            max_index, max_class, max_prob))

    # render page
    return render_template('upload_output.html',
                           filename=filename,
                           url=url,
                           predictions=predictions,
                           max_class=max_class,
                           max_prob=max_prob)
    def process(self, obj):

        imgstr = obj['payload']

        img = Image.open(BytesIO(b64decode(imgstr)))

        if img.mode != "RGB":
            img = img.convert("RGB")
        # resize the input image and preprocess it
        img = img.resize((224, 224))
        img = image.img_to_array(img)
        img = np.expand_dims(img, axis=0)
        img = preprocess_input(img)

        with graph.as_default():
            set_session(sess)
            predictions = model.predict(img)

        predictions = decode_predictions(predictions, top=3)[0]
        print("Predictions from class_model_server.py:", predictions)

        pred_strings = []
        for _, pred_class, pred_prob in predictions:
            pred_strings.append(
                str(pred_class).strip() + " : " +
                str(round(pred_prob, 5)).strip())
        preds = ", ".join(pred_strings)

        return_dict = {}
        return_dict["preds"] = preds
        return return_dict
def upload():
    if request.method == 'POST':
        f = request.files['photo']

        basepath = os.path.dirname(__file__)
        file_path = os.path.join(basepath, 'uploads',
                                 secure_filename(f.filename))
        f.save(file_path)

        x = preprocess_image(file_path)

        out = model.predict(x)
        u = decode_predictions(out, top=3)[0]
        s1 = u[0][1]
        s2 = u[0][2] * 100
        s3 = u[1][1]
        s4 = u[1][2] * 100
        s5 = u[2][1]
        s6 = u[2][2] * 100
        print(s1, s2, s3)
        return render_template("index2.html",
                               s1=s1,
                               s2=s2,
                               s3=s3,
                               s4=s4,
                               s5=s5,
                               s6=s6)
예제 #10
0
def index():
    menu = {
        'ho': 1,
        'da': 0,
        'ml': 0,
        'se': 0,
        'co': 0,
        'cg': 0,
        'cr': 0,
        'st': 0,
        'wc': 0
    }
    vgg16 = VGG16()
    names = []
    vgg16_list = []
    for file in glob(
            'D:/Workspace/Python_flask/04.MachineLearning/static/data_01/*'):
        name = file.split('.')[1]
        name = name.split('\\')[1]
        names.append(name)

        img = io.imread(file)
        # 불안정함
        # img = cv2.imread(file, -1)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = cv2.resize(img, (224, 224))

        yhat = vgg16.predict(img.reshape(-1, 224, 224, 3))
        label = decode_predictions(yhat)
        label = label[0][0]
        label_per = f'{label[1]}({round(label[2]*100, 1)}%)'
        vgg16_list.append(label_per)
    return vgg16_list[0]
예제 #11
0
def classify_process():
    model = ResNet50(weights='imagenet')

    while True:
        queue = db.lrange(IMAGE_QUEUE, 0, BATCH_SIZE - 1)
        imageIDs = []
        batch = None

        for q in queue:
            q = json.loads(q.decode('utf-8'))
            image = base64_decode_image(q['image'], IMAGE_DTYPE, (1, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANS))

            if batch is None:
                batch = image
            else:
                batch = np.vstack([batch, image])
            imageIDs.append(q["id"])

            if len(imageIDs) > 0:
                print(" * Batch size: {}".format(batch.shape))
                preds = model.predict(batch)
                results = decode_predictions(preds)

                for (imageID, resultSet) in zip(imageIDs, results):
                    output = []
                    for (imagenetID, label, prob) in resultSet:
                        r = {"label": label, "probability": float(prob)}
                        output.append(r)
                    db.set(imageID, json.dumps(output))

                db.ltrim(IMAGE_QUEUE, len(imageIDs), -1)
            time.sleep(SEVER_SLEEP)
def imageProcess(request):
    form = ImageUploadingForm(request.POST, request.FILES)
    if form.is_valid():
        handle_upload(request.FILES['image'])

        # if image valid, create model
        model = ResNet50(weights='imagenet')

        img_path = 'img.jpg'

        # predicting image
        img = image.load_img(img_path, target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)

        preds = model.predict(x)
        # print('Predicted:', decode_predictions(preds, top=3)[0])

        res = []
        for result in decode_predictions(preds, top=3)[0]:
            res.append((result[1], np.round(result[2] * 100, 2)))

        # print(res)

    return render(request, 'image-process/output.html', {'res': res})
def verify_with_image(model, input_shape):
    from tensorflow.keras.applications.resnet50 import decode_predictions
    from PIL import Image
    while True:
        img_file = input('Input image filename:')
        try:
            img = Image.open(img_file).convert('RGB')
            resized_img = img.resize(input_shape, Image.BICUBIC)
        except:
            print('Open Error! Try again!')
            continue
        else:
            img_array = np.asarray(resized_img).astype('float32')
            x = normalize_image(img_array)
            preds = model.predict(np.expand_dims(x, 0))

            result = decode_predictions(preds)
            print('Predict result:', result)

            # show predict result on origin image
            img_array = np.asarray(img)
            cv2.putText(img_array,
                        '{name}:{conf:.3f}'.format(name=result[0][0][1],
                                                   conf=float(
                                                       result[0][0][2])),
                        (10, 30),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=1,
                        color=(255, 0, 0),
                        thickness=2,
                        lineType=cv2.LINE_AA)
            Image.fromarray(img_array).show()
예제 #14
0
def benchmark_saved_model(SAVED_MODEL_DIR, batch_size=4):
    image_x = []
    for i in range(batch_size):
        img_path = './data/img%d.JPG' % (i % 4)
        img = image.load_img(img_path, target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        image_x.append(x)
    with tf.Session(graph=tf.Graph(), config=config) as sess:

        tf.compat.v1.saved_model.loader.load(sess, [tf.saved_model.SERVING],
                                             SAVED_MODEL_DIR)
        start = time.time()
        for i in range(batch_size):
            img_path = './data/img%d.JPG' % (i % 4)
            img = image.load_img(img_path, target_size=(224, 224))
            x = image.img_to_array(img)
            x = np.expand_dims(x, axis=0)
            x = preprocess_input(x)
            output = sess.run(OUTPUT_TENSOR, feed_dict={INPUT_TENSOR: x})
            print(type(output))
            print(output.shape)
            print(decode_predictions(output, top=3)[0])
        end = time.time()
        print("processing time = {}ms".format((end - start) / 4 * 1000))
예제 #15
0
파일: test_video.py 프로젝트: lc0/io
def test_video_predict():
    model = ResNet50(weights='imagenet')
    x = VideoDataset(video_path).batch(1).map(
        lambda x: preprocess_input(image.resize(x, (224, 224))))
    y = model.predict(x)
    p = decode_predictions(y, top=1)
    assert len(p) == 166
예제 #16
0
def dl_submit():
    img = request.files["image"]
    img.save("./myimage")

    image = tf.image.decode_image(tf.io.read_file("./myimage"))
    image = tf.image.resize(image, [224, 224])
    pre_image = preprocess_input(image)
    # make as 4D
    pre_image = pre_image[None, ...]

    b = tf.image.decode_image(tf.io.read_file("./myimage"))
    jpeg = tf.image.encode_jpeg(b)
    b = base64.b64encode(jpeg.numpy()).decode("utf-8")

    probas = app.dl_model.predict(pre_image)
    x = decode_predictions(probas, top=5)
    print(x)

    x = [(i[1], i[2] * 100) for i in x[0]]

    return (f"""<!doctype html>
    <title>ResNet50 Image Prediction</title>
    <img src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Flask_logo.svg" alt="alternatetext" width="200" height="200">
    <body style="background-color:powderblue;">
    Predicted class image is (with probability): <b>{x}</b> <br>
    <img src='data:image/jpeg;base64,{b}'>
    """ + """<br><a href='/'>Go Back</a>""")
예제 #17
0
def test():
    f = flask_request.files['file']
    img = np.fromstring(f.read(), np.uint8)
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    img = prepare_image(img)
    pred = model.predict(img)
    return str(decode_predictions(pred))
def run_resnet_model(img_path):
    img = image.load_img(path=img_path, target_size=(224, 224))
    X = image.img_to_array(img)
    X = np.expand_dims(X, axis=0)
    X = resnet50.preprocess_input(X)
    X_pred = model_resnet.predict(X)
    display_prediction(resnet50.decode_predictions(X_pred, top=1))
예제 #19
0
def classify(img_path):
    display(Image(filename=img_path))
    img = image.load_img(img_path,target_size=(224,224))
    x=image.img_to_array(img)
    x=np.expand_dims(x,axis=0)
    x=preprocess_input(x)
    predict=model.predict(x)
    print('predicted',decode_predictions(predict,top=3)[0])
def classify(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    model = tf.keras.applications.resnet50.ResNet50()
    img_array = image.img_to_array(img)
    img_batch = np.expand_dims(img_array, axis=0)
    img_preprocessed = preprocess_input(img_batch)
    prediction = model.predict(img_preprocessed)
    print(decode_predictions(prediction, top=3)[0])
예제 #21
0
def classify(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    img_array = image.img_to_array(img)
    img_batch = np.expand_dims(img_array, axis=0)
    img_preprocessed = preprocess_input(img_batch)
    model = tf.keras.models.load_model('./models/resnet50.h5')
    prediction = model.predict(img_preprocessed)
    return decode_predictions(prediction, top=3)[0]
예제 #22
0
def score_model(model, x):
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    predictions = model.predict(x)
    result = {
      "result": [ [x[1], round(x[2] * 100, 2)] for x in decode_predictions(predictions, top=3)[0]]
    }
    return result
 def decode_predictions_top_five(prediction):
     decoded_prediction = decode_predictions(prediction, top=5)[0]
     
     #prediction list of class name and class probability
     prediction_list = []
     for i in range(5):
         prediction_list.append(decoded_prediction[i][1:3])
         
     return prediction_list
예제 #24
0
def test():
    f = flask_request.files['file']
    img = np.fromstring(f.read(), np.uint8)
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    img = prepare_image(img)
    img = tf.constant(img)
    labeling = infer(img)
    pred = labeling['predictions'].numpy()
    return str(decode_predictions(pred))
예제 #25
0
def classify_image(img):
    resized = np.array(Image.fromarray(img).resize((224, 224)))
    x = np.expand_dims(image.img_to_array(resized), axis=0)
    x = preprocess_input(x)

    preds = model.predict(x)

    results = decode_predictions(preds, top=3)[0]
    return "Predicted: {}".format(','.join([x[1] for x in results]))
예제 #26
0
def get_image_predictions(img_raw):
    img = cv2.resize(img_raw, (224, 224))

    x = img
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)

    preds = model.predict(x)

    return decode_predictions(preds, top=3)[0]
예제 #27
0
def predict():
    if request.method == 'POST':
        image_file = request.files['file'].read()
        if image_file:
            image_array = np.fromstring(image_file, np.uint8)
            image_decode = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
            x = prepare_image(image_decode)
            predicts = model.predict(x)
            results = decode_predictions(predicts)
            return str(results)
예제 #28
0
 def _post_process(self, prediction: np.array) -> PredictionResult:
     """post process
     Args:
         prediction (np.array): result of predict
     Returns:
        PredictionResult: prediction
     """
     result_label = decode_predictions(prediction, top=1)[0][0][1]
     dcp = PredictionResult(name=result_label)
     return dcp
예제 #29
0
def get_top_5_predictions(img):
    x = img_to_array(img)[np.newaxis, ...]
    x = preprocess_input(x)
    preds = decode_predictions(model.predict(x), top=5)
    top_preds = pd.DataFrame(columns=['prediction', 'probability'],
                             index=np.arange(5)+1)
    for i in range(5):
        top_preds.loc[i+1, 'prediction'] = preds[0][i][1]
        top_preds.loc[i+1, 'probability'] = preds[0][i][2]
    return top_preds
예제 #30
0
def get_classes(file_path):

    img = image.load_img(file_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.array([x])
    x = preprocess_input(x)

    preds = model.predict(x)
    predictions = decode_predictions(preds, top=3)[0]
    print(predictions)
    return predictions