예제 #1
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)
        img1 = base64_to_pil(request.json)
        #cam(img1)
        preds = model_predict(img, model)
        # Process your result for human
        pred_class = decode_predictions(preds)  # ImageNet Decode
        result = str(pred_class[0][0][1])  # Convert to string
        result = result.replace('_', ' ').capitalize()
        return jsonify(result=result)  #, probability=pred_proba)
    return None
예제 #2
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        print(request.json)
        print('aaa')
        img1, img2 = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img1, img2, model)

        # Process your result for human
        # pred_proba = "{:.3f}".format(np.amax(preds))    # Max probability

        # result = str(pred_class[0][0][1])               # Convert to string
        # result = result.replace('_', ' ').capitalize()

        # Serialize the result, you can add additional fields
        type(preds)
        result = preds
        # lists = result.tolist()
        # json_str = json.dumps(lists)
        # print(json_str)
        print(result)
        return jsonify(result)

    return None
예제 #3
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        model_xception = load_model(MODEL_XCEPTION)
        img = base64_to_pil(request.json)
        preds = model_predict(img, model_xception)
        # Save the image to ./uploads
        # img.save("./uploads/image.png")
        # Make predictionpy

        #preds = model_predict(img, model
        # Process your result for human
        pred_proba = "{:.3f}".format(np.amax(preds))  # Max probability
        classes = [
            'Abyssinian', 'Bengal', 'Bombay', 'British Shorthair',
            'Egyptian Mau', 'Maine Coon', 'Persian', 'Russian Blue', 'Siamese',
            'Sphynx'
        ]

        #result = str(classes[0][0][1])               # Convert to string
        #result = str(classes[np.argmax(np.array(preds[0]))])
        #result = result.replace('_', ' ').capitalize()

        result = []
        for idx in preds.argsort()[0][::-1][:3]:
            arr = classes[idx].split("-")[-1] + ' : ' + "{:.2f}%\n".format(
                preds[0][idx] * 100)
            #arr = [ '\n{}'.format(x) for x in arr ]
            result.append(arr)
        a = "Used Model: Xception"
        # Serialize the result, you can add additional fields
        return jsonify(result=result, prediction=pred_proba, a=a)
        return render_template("index.html", a=a)
예제 #4
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)
        print("b/m", preds)

        # Process your result for human
        pred_proba = "{:.3f}".format(np.amax(preds))    # Max probability
        #pred_class = decode_predictions(preds, top=1)   # ImageNet Decode
        print("pred_proba", pred_proba)
        print(type(preds[0]))

        if float(preds[0][1]) >= 0.5:
            result = "malignant"
        else:
            result = "benign"


        # Serialize the result, you can add additional fields
        return jsonify(result=result, probability=pred_proba)

    return None
예제 #5
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)

        # Process your result for human
        if preds == 0:
            result = 'No DR'
        elif preds == 1:
            result = 'Mild'
        elif preds == 2:
            result = 'Moderate'
        elif preds == 3:
            result = 'Severe'
        else:
            result = 'Proliferative DR'
        # Serialize the result, you can add additional fields
        return jsonify(result=result)

    return None
예제 #6
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")   
        # Make prediction
        
        #preds = model_predict(img, model)
        preds = loadModel(img)
        
        # Process your result for human
        pred_proba = "{:.3f}".format(np.amax(preds))    # Max probability
        classes = ['Abyssinian', 'Bengal', 'Bombay', 'British Shorthair', 'Egyptian Mau', 'Maine Coon', 'Persian', 'Russian Blue', 'Siamese', 'Sphynx']

        #result = str(classes[0][0][1])               # Convert to string
        result = str(classes[np.argmax(np.array(preds[0]))])
        result = result.replace('_', ' ').capitalize()
        
        ngetes = []
        for idx in preds.argsort()[0][::-1][:5]:
            arr = classes[idx].split("\n-")[-1],"\n{:.2f}%\n".format(preds[0][idx]*100)
            #arr = [ '\n{}'.format(x) for x in arr ]
            ngetes.append(arr)
       
        # Serialize the result, you can add additional fields
        return jsonify(result=ngetes, probability=pred_proba)

    return None
예제 #7
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)

        # Process your result for human
        pred_proba = "{:.3f}".format(np.max(preds[0], axis=-1))    # Max probability
        print("Maximum Probability: ",pred_proba)
        # pred_class = decode_predictions(preds, top=1)   # ImageNet Decode

        # result = str(pred_class[0][0][1])               # Convert to string
        # result = result.replace('_', ' ').capitalize()

        labels = {0: 'Garbage Image', 1: 'Non-Garbage Image'}
        result = labels[np.argmax(preds[0], axis=-1)]
        print("Classified:",result)
        
        # Serialize the result, you can add additional fields
        return jsonify(result=result, probability=pred_proba)

    return None
예제 #8
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)
        print(preds)

        # Process your result for human
        pred_proba = "{:.3f}".format(np.amax(preds))  # Max probability
        print(pred_proba)

        threshold = .5
        if preds[0] > threshold:
            result = 'bacterial'
        else:
            result = 'viral'

        # pred_class = decode_predictions(preds, top=1)   # ImageNet Decode

        # result = str(pred_class[0][0][1])               # Convert to string
        # result = result.replace('_', ' ').capitalize()

        # Serialize the result, you can add additional fields
        return jsonify(result=result, probability=pred_proba)

    return None
예제 #9
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)
        # Save the image to ./uploads
        # img.save("./uploads/image.png")
        # Make prediction
        preds = get_embedding(model, img)
        f = open('store.pckl', 'rb')
        df, df_embs = pickle.load(f)
        f.close()
        # append extracted features to dataset
        df_embs = df_embs.append(pd.Series(preds), ignore_index=True)
        # compute cos similarities between objects:
        cosine_sim = 1 - pairwise_distances(df_embs, metric='cosine')
        # indices = pd.Series(range(len(df)), index=df.index)
        # return top-10 similar items for input image. It's index in the dataframe is 5000 (the last row)
        #idx_rec, idx_sim = get_recommender(5000, df, cosine_sim, indices, top_n=10)
        top_n = 5
        sim_scores = list(enumerate(cosine_sim[-1]))
        sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
        sim_scores = sim_scores[1:top_n + 1]
        idx_rec = [i[0] for i in sim_scores]
        idx_sim = [i[1] for i in sim_scores]

        out = df[['images.model', 'shortDescription',
                  'priceInfo.finalPrice']].loc[idx_rec].to_json(orient='index')
        # Serialize the result, you can add additional fields
        return jsonify(out)

    return None
예제 #10
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Make prediction
        preds = model_predict(img, model)

        if preds == 0:
            result = "MEL"
        elif preds == 1:
            result = "NV"
        elif preds == 2:
            result = "BCC"
        elif preds == 3:
            result = "AK"
        elif preds == 4:
            result = "BKL"
        elif preds == 5:
            result = "DF"
        elif preds == 6:
            result = "VASC"
        elif preds == 7:
            result = "SCC"
        else:
            result = "UNK"

        return jsonify(result=result, probability=int(preds))

    return None
예제 #11
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json).convert('RGB')
        #print(request.files['file'])

        # Save the image to ./uploads
        #img.save("uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)
        gradcam = gradcam_from_img(img)
        # Process your result for human
        if (preds[0][0] >= preds[0][1]):
            pred_class = "POSITIVE"
        else:
            pred_class = "NEGATIVE"

        pred_proba = "{:.3f}".format(np.amax(preds))  # Max probability

        # Serialize the result, you can add additional fields
        return jsonify(result=pred_class,
                       probability=pred_proba,
                       file=img_to_base64(gradcam))

    return None
예제 #12
0
def predict():
    try:
        img = base64_to_pil(request.json)
    except Exception:
        return jsonify(error="expected string or bytes-like object"), 422

    rgb_image_np = np.array(img.convert('RGB'))
    stds = rgb_image_np.std(axis=(0, 1))
    means = rgb_image_np.mean(axis=(0, 1))
    if 35 < np.average(stds) < 95 and 60 < np.average(means) < 180:
        img_result = x_ray.predict(img)
        condition_similarity_rate = []
        if img_result['condition rate'] == []:
            return jsonify(
                result='NOT DETECTED',
                error='Invalid image'
            ), 200
        else:
            for name, prob in img_result['condition rate']:
                condition_similarity_rate.append({'y': round(float(prob), 3), 'name': name})
            print(condition_similarity_rate)
            return jsonify(
                condition_similarity_rate=condition_similarity_rate
            ), 200
    else:
        file_name = "NOT_DETECTED/%s.jpg" % str(uuid.uuid4())
        return jsonify(
            result='NOT DETECTED',
            error='Invalid image'
        ), 200
예제 #13
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)
        preds = np.argmax(preds, axis=1)

        # Process your result for human

        pred_class = [
            ":( Oops, Not a Cat",
            ":) Yes, It's a Cat!",
        ]  # ImageNet Decode

        result = [pred_class[index] for index in preds]  # Convert to string

        # Serialize the result, you can add additional fields
        return jsonify(result=result[0])

    return None
예제 #14
0
def predict():
    if request.method == 'POST':

        # Get the image from post request
        img = base64_to_pil(request.json)

        img.save("uploads\image.jpg")

        img_path = os.path.join(os.path.dirname(__file__), 'uploads\image.jpg')

        os.path.isfile(img_path)

        img = image.load_img(img_path, target_size=(64, 64))

        preds = model_predict(img, model)

        result = preds[0, 0]

        print(result)

        if result > 0.5:
            return jsonify(result="PNEMONIA")
        else:
            return jsonify(result="NORMAL")

    return None
예제 #15
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        image = base64_to_pil(request.json['image'])
        height = int(request.json['height'])

        if not os.path.exists('../_tmp/in'):
            tf.gfile.MakeDirs('../_tmp/in')

        image.save('../_tmp/in/work.png')

        # res_im,seg=MODEL.run(image)

        # seg=cv2.resize(seg.astype(np.uint8),image.size)
        # mask_sel=(seg==15).astype(np.float32)
        # mask = 255*mask_sel.astype(np.uint8)

        # img = 	np.array(image)
        # img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

        # res = cv2.bitwise_and(img,img,mask = mask)
        # bg_removed = res + (255 - cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR))
        # result = main(bg_removed,height,None)

        result = demo.run('../_tmp/in', height)
        obj = ''
        with open('test.obj', 'r') as file:
            obj = file.read()
        return jsonify(result=result, obj=obj)

    return None
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model1)

        switcher = {
            0: "Airplane",
            1: "auto-mobile",
            2: "Bird",
            3: "Cat",
            4: "Deer",
            5: "Dog",
            6: "Frog",
            7: "Horse",
            8: "Ship",
            9: "Truck"
        }

        result = switcher.get(int(preds), "Nothing")
        # Serialize the result, you can add additional fields
        return jsonify(result=result)

    return None
예제 #17
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        # img.save("./uploads/image.png")

        # Make prediction
        preds = model_predict(img, model)
        pred_class = np.argmax(preds, axis=1)

        # Process your result for human
        pred_proba = "{:.3f}".format(np.amax(preds))  # Max probability
        #pred_class = decode_predictions(preds, top=1)   # ImageNet Decode

        if pred_class == 0:
            result = 'Not subluxed'
        elif pred_class == 1:
            result = 'Subluxed'

        #result = str(pred_class[0][0][1])               # Convert to string
        result = result.replace('_', ' ').capitalize()

        # Serialize the result, you can add additional fields
        return jsonify(result=result, probability=pred_proba)

    return None
예제 #18
0
def upload_backend(label):
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)
        img.save("uploads/" + label + "/" + str(secrets.token_hex(32)) +
                 ".png")
        return jsonify(result="Thank you!")
    return None
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)
        # Make prediction
        return model_predict(img)

    return None
예제 #20
0
def predict():
    if request.method == 'POST':
        img1, img2 = base64_to_pil(request.json)
        img3 = model_predict(img1, img2)
        img3 = cv2.resize(img3, (400, 300), interpolation=cv2.INTER_AREA)
        img3 = np_to_base64(img3)
        #return jsonify({'image_url': '/output.png'})
        return jsonify(img3)
    return None
예제 #21
0
def predict():
    if request.method == 'POST':
        # print(request.json)  # data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QAIRXhpZgAA/9sAQwAFAwQEBAM

        # # Get the image from post request
        # img = base64_to_pil(request.json)
        img = base64_to_pil(request.json).convert('L').resize((48, 48))
        img = np.asarray(img).reshape(-1, 48, 48, 1).astype('float32') / 255
        # print(img.shape)

        # # # Save the image to ./uploads
        # img.save("./uploads/image.png")
        begin = time.time()
        p_class = predict_class(img)
        predict_time1 = time.time()
        p_value = predict_value(img)
        predict_time2 = time.time()
        print("time:",str(predict_time1-begin),str(predict_time2-begin))
        print("预测结果(lable):", p_class)
        print("预测结果:", label_dict[p_class[0]])
        print("每个预测值:", p_value)

        # 终端显示每个预测结果对应的预测值
        # probability_yang = show_predict_result(p_class, p_value)


        # prediction = model.predict_classes(img)
        # prediction_probability = model.predict(img)
        # print(prediction)
        # print(prediction_probability)

        # # # Make prediction
        # preds = model_predict(img, model)
        #
        # # Process your result for human
        # probability = "{:.3f}".format(np.amax(p_class[0]))  # Max probability
        # pred_class = decode_predictions(preds, top=1)  # ImageNet Decode
        #
        result = str(label_dict[p_class[0]])  # Convert to string
        result = result.replace('_', ' ').capitalize()
        # probability =str(p_value)
        # probability= json.dumps(p_value.item())
        # probability=p_value.tolist()

        # probability = str(p_value)  # Convert to string
        # probability = probability.replace('_', ' ').capitalize()
        probability = str(",".join(str(float(_*100)) for _ in p_value[0]))



        print(result)
        print(probability)
        # print(result)
        # # Serialize the result, you can add additional fields
        return jsonify(result=result, probability=probability)
        # return jsonify(result=result, probability=probability.yang)
    return None
예제 #22
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)
        preds = model_predict(img, test)
        result = str(preds)
        return jsonify(result=result)
    print("end")
    return None
예제 #23
0
def predict():
    # 需要从request对象读取表单内容:
    if request.method == 'POST':
        render_template('index.html')
        img = base64_to_pil(request.json)
        prediction = model_predict(img, model).numpy().item()
        prediction_class = class_map[prediction]
        return jsonify(result=prediction_class)

    return '<h3>Bad username or password.</h3>'
예제 #24
0
def predict():
    if request.method == 'POST':
        img = base64_to_pil(request.json)
        hash_value = str(hex(hash(img.tobytes())))
        response = inference_handler.predict(img)
        storage.temp_store(hash_value, img)

        return jsonify(result=response, hash_value=hash_value)

    return None
def findEdge():
    img = base64_to_pil(request.form['image'])
    target = np.array([request.form['x'], request.form['y']], dtype=float)
    nearestPoint, distance = find_nearest_white(img, target)
    result = {
        'x': int(nearestPoint[0]),
        'y': int(nearestPoint[1]),
        'distance': float(distance)
    }
    return jsonify(result)
예제 #26
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Make prediction
        ##preds = model_predict(img, model)
        pred_proba = model_predict(img, model)

        pred_class = np.argmax(pred_proba)
        # Process your result for human
        ##pred_proba = "{:.3f}".format(np.amax(preds))    # Max probability
        pred_proba = "{:.3f}".format(np.argmax(pred_proba))

        if pred_class < 0.9:
            result = 'No_fire'
        elif pred_class >= 0.9:
            result = 'Fire'
            sendEmail()

        #Make threshold basis results coming along

        result = result.replace('_', ' ').capitalize()

        #sendEmail()

        # Process your result for human
        ##pred_proba = "{:.3f}".format(np.amax(preds))    # Max probability
        ##pred_class = decode_predictions(preds, top=1)   # ImageNet Decode

        ##result = str(pred_class[0][0][1])               # Convert to string
        ##result = result.replace('_', ' ').capitalize()

        # Serialize the result, you can add additional fields

        this_image = f"./images/{datetime.now().timestamp()}.png"

        ################# ACTION: SAVE YOUR MASKED IMAGE HERE ##################
        #Watever function you have change the `img.save`
        img.save(this_image)
        ################# ACTION END ##################

        image_file = open(this_image, "rb")
        image = base64.b64encode(image_file.read())
        image_string = str(
            image
        )[2:
          -1]  #converting it into string and removing the 'b' and the quotes from the start and end

        return jsonify(result=result,
                       probability=pred_proba,
                       image=image_string)

    return None
예제 #27
0
def predict():
    if request.method == 'POST':
        img = base64_to_pil(request.json)
        img.save("uploads/" + filename + ".png")
        preds = model_predict(img, model)
        pred_proba = "{:.3f}".format(np.amax(preds))
        pred_class = decode_predictions(preds, top=1)
        result = str(pred_class[0][0][1])
        result = result.replace('_', ' ').capitalize()
    searchterm = result
    directory = "./images/"
    url = "https://www.google.co.in/search?q=" + searchterm + "&source=lnms&tbm=isch"
    browser = webdriver.Chrome('C:\WebDrivers\chromedriver.exe')
    browser.get(url)
    extensions = {"jpg", "jpeg", "png", "gif"}
    if not os.path.exists(directory):
        os.mkdir(directory)
    for _ in range(500):
        browser.execute_script("window.scrollBy(0,10000)")
    html = browser.page_source.split('["')
    imges = []
    for i in html:
        if i.startswith('http') and i.split('"')[0].split(
                '.')[-1] in extensions:
            imges.append(i.split('"')[0])
    print(imges)

    def save_image(img, directory):
        for img in imges:
            img_url = img
            img_type = img.split('.')[-1]
            try:
                path = os.path.join(
                    directory,
                    searchterm + "_" + str(uuid.uuid4()) + "." + 'jpg')
                urllib.request.urlretrieve(img, path)
            except Exception as e:
                print(e)

    save_image(imges, directory)
    browser.close()
    fantasy_zip = zipfile.ZipFile('C:\\Users\\User\\Desktop\\FYP\\images.zip',
                                  'w')

    for folder, subfolders, files in os.walk(
            'C:\\Users\\User\\Desktop\\FYP\\images'):

        for file in files:
            if file.endswith('.jpg'):
                fantasy_zip.write(os.path.join(folder, file),
                                  file,
                                  compress_type=zipfile.ZIP_DEFLATED)
    fantasy_zip.close()
    return jsonify(result=result, probability=pred_proba)
예제 #28
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Make prediction
        preds = model_predict(img, model)
        labels = {'glioma': 0, 'meningioma': 1, "no_tumor":2,'pituitary': 3}
        prediction = list(labels.keys())[list(labels.values()).index(list(preds)[0])]
        result = str(prediction)               # Convert to string
        result = result.replace('_', ' ').capitalize()
        return jsonify(result=result,preds = str(list(preds)))
예제 #29
0
def predict():
    if request.method == 'POST':
        img = base64_to_pil(request.json)
        print(img.filename)
        path = 'image.jpg'
        img.save(path)
        result = neural.predict_breed(path)

        # Serialize the result
        return jsonify(result=result)

    return None
예제 #30
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json).convert('RGB')
        img.save("./uploads/image.jpg")
        # Make prediction
        #----------IDS PREDICTIONS -----------------
        IDs = IDs_Predictions(img)

        #-------------------------------------------
        return jsonify(IDS=(IDs))
        #return jsonify(result=(max_predicted_class, probability=pred_proba))
    return None