Exemple #1
0
def predictions():
    test_dir = "stage_2_test_images/"
    test_list = os.listdir(test_dir)

    model = load_model("pneumonia_model.h5")

    predict_list = []
    for img_name in test_list:
        dicom_img = pydicom.dcmread(test_dir + img_name)
        img = dicom_img.pixel_array.astype(float)

        rescale_image = (np.maximum(img, 0) / img.max()) * 255
        image_rescaled = np.uint8(rescale_image)

        image = Image.fromarray(image_rescaled)
        NEW_SIZE = (256, 256)
        final_img = image.resize(NEW_SIZE)
        test_arr = np.array(final_img)
        test_arr = test_arr.reshape(-1, 256, 256, 1)
        prediction = model.predict(test_arr)
        predict_list.append(int(prediction))

    predict_df = pd.DataFrame(test_list, columns=['patientId'])
    predict_df['PredictionString'] = predict_list
    print(predict_df)
    predict_df.to_csv('chest_xray_pneumonia_predictions.csv')
def classify_img(self, filename):

    MY_GRAPH = tf.compat.v1.get_default_graph()

    json_file = open("model.json", 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    model = model_from_json(loaded_model_json)
    model.load_weights("model.h5")
    image = Image.open(BytesIO(redis_store.get(filename)))
    image = image.resize((150, 150))
    image = np.array(image)
    image = image[..., :3]
    image = np.expand_dims(image, axis=0)
    images = np.vstack([image])
    images = images / 255

    with MY_GRAPH.as_default():
        json_file = open("model.json", 'r')
        loaded_model_json = json_file.read()
        json_file.close()
        model = model_from_json(loaded_model_json)
        model.load_weights("model.h5")
        model.compile(loss='binary_crossentropy',
                      optimizer='rmsprop',
                      metrics=['acc'])
        classes = model.predict(images)
    if classes[0] > 0.5:
        return "human"
    else:
        return "horse"
Exemple #3
0
def index(request):
    prediction=''
    if request.POST:
        module_dir = os.path.dirname(__file__) 
        file1_path, file1_name = handle_uploaded_file(request.FILES['file1'])
        json_file = open(os.path.join(module_dir,'model.json'))
        model_file =os.path.join(module_dir,'model.h5')
        loaded_model_json = json_file.read()
        json_file.close()
        loaded_model = model_from_json(loaded_model_json)
        # load weights into new model
        loaded_model.load_weights(model_file)   
        # img = image.load_img(file1_path, target_size=(150,150))
        # x = image.img_to_array(img)
        # x = np.expand_dims(x, axis=0)
        # x = preprocess_input(x)
        image = Image.open(file1_path)
        image = image.resize((150,150),Image.ANTIALIAS)
        nd_array = np.array(image)
        nd_array_lst = convert_to_ndarry([nd_array,])
        preds = loaded_model.predict(nd_array_lst)
        if preds[0]>0:
            # print(preds + " is  wearglass")
            prediction="Wear Eye glass"
        else:
            # print(preds + " is notwearglass")
            prediction="Not Wear Eye glass"
        return render(request, "index.html", {"prediction":prediction,
                                              "post": True,
                                              "img1src": file1_name,
                                              })
    return render(request, "index.html", {'post': False})
Exemple #4
0
def app():
    new_model = keras.models.load_model("haemorrhage_modelnorm.h5")
    st.title("Haemorrhage Detection")
    page_bg_img = '''
	<style>
	body {
	background-image: url("https://img.freepik.com/free-vector/white-elegant-texture-wallpaper_23-2148421854.jpg?size=626&ext=jpg&ga=GA1.2.145878890.1611360000");
	background-size: cover;
	}
	</style>
	'''

    st.markdown(page_bg_img, unsafe_allow_html=True)

    uploaded_file_hem = st.file_uploader("Choose a image file",
                                         type=['png', 'jpg', 'jpeg'])
    if uploaded_file_hem is not None:
        image = Image.open(uploaded_file_hem)
        size = (128, 128)
        image1 = image.resize(size)
        image1 = ImageOps.grayscale(image1)
        x = np.asarray(image1)
        x = np.expand_dims(x, axis=0)
        x = np.reshape(x, (1, 128, 128, 1))
        x = x / 255.0
        if (new_model.predict_classes(x)[0][0] == 1):
            st.write('***Haemorrhage***')
            if st.button('Show Image'):
                st.image(image, channels='BGR', width=300)
        else:
            st.write('***Normal***')
            if st.button('Show Image'):
                st.image(image, channels='BGR', width=300)
Exemple #5
0
def app():
    new_model = keras.models.load_model("modelpncnn.h5")
    st.title("Pneumonia Detection")
    #st.markdown(html, unsafe_allow_html=True)

    uploaded_file = st.file_uploader("Choose a image file",
                                     type=['png', 'jpg', 'jpeg'])
    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        #st.image(image,channels='BGR')

        #images = image.load_img(img, target_size=(150,150))
        #x = image.img_to_array(images)
        #x = tf.image.rgb_to_grayscale(x)
        #x = np.expand_dims(x, axis=0)
        #x = x/255.0
        size = (150, 150)
        #image1 = ImageOps.fit(img, size, Image.ANTIALIAS)
        image1 = image.resize(size)
        image1 = ImageOps.grayscale(image1)
        x = np.asarray(image1)
        x = np.expand_dims(x, axis=0)
        x = np.reshape(x, (-1, 150, 150, 1))
        x = x / 255.0
        if (new_model.predict_classes(x)[0][0] == 1):
            st.write('***Normal***')
            if st.button('Show Image'):
                st.image(image, channels='BGR', width=300)
        else:
            st.write('***Pneumonia***')
            if st.button('Show Image'):
                st.image(image, channels='BGR', width=300)
Exemple #6
0
def prep_image(image, target):
    if (image.mode != "RGB"):
        image = image.convert("RGB")
    image = image.resize(target)
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    image = imagenet_utils.preprocess_input(image)
    return image
Exemple #7
0
def save_image(results_paths, output_dir='../output/'):
    print(f'==> Result image saved to {output_dir}')
    combined = Image.new("RGB",
                         (IMAGE_WIDTH * len(results_paths), IMAGE_HEIGHT))
    x_offset = 0
    for image in map(Image.open, results_paths):
        combined.paste(image.resize((IMAGE_WIDTH, IMAGE_HEIGHT)),
                       (x_offset, 0))
        x_offset += IMAGE_WIDTH
    combined.save(output_dir)
def form():
    form = Form()
    if request.method == 'POST':
        if request.files.get("image"):
            image1 = request.files["image"].read()
            image = Image.open(io.BytesIO(image1))
            image = image.resize((130, 130))
            results = return_predictions(model, image)
            # print(image)
            return render_template('prediction.html', results=results)
    return render_template('home.html', form=form)
Exemple #9
0
def preprocess_image(image, target_size):
    '''function to preprocess input image'''
    if image.mode != "RGB":
        image = image.convert("RGB")  # if image is not RGB then convert to RGB
    image = image.resize(target_size)  # resize image to defined target size
    # image = image.img_to_array(image)  # convert image to an array of numbers
    image = asarray(image)
    image = image.astype(np.float32)  # convert from uint8 to float32
    image = np.expand_dims(image, axis=0)  # expand the dimension of the image

    return image
Exemple #10
0
def process_image(image):
    #read image
    image = Image.open(BytesIO(image))
    if image.mode != "RGB":
        image = image.convert("RGB")

    # resize and convert to tensor
    image = image.resize((96, 96))
    image = img_to_array(image)
    image = preprocess_input(image)
    image = np.expand_dims(image, axis=0)
    return image
def convert_image_to_array(image_dir):
    try:
        image = Image.open(image_dir)
        #st.image(image,channels='BGR')
        if image is not None:
            image = image.resize(default_image_size)
            return img_to_array(image)
        else:
            return np.array([])
    except Exception as e:
        print(f"Error : {e}")
        return None
Exemple #12
0
def prepare_image(image, target):
    # if the image mode is not RGB, convert it
    if image.mode != "RGB":
        image = image.convert("RGB")

    # resize the input image and preprocess it
    image = image.resize(target)
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    image = imagenet_utils.preprocess_input(image)

    # return the processed image
    return image
    def get(self, user_index):

        credentials_json = open("credentials.json", "rb")
        config = pickle.load(credentials_json)
        credentials_json.close()

        MODEL_PATH = 'models/covid_new_model1.model'

        # Load your own trained model
        model = load_model(MODEL_PATH)
        model._make_predict_function()

        firebase = pyrebase.initialize_app(config)
        db = firebase.database()
        nm = db.child("Appointments").child(user_index).get()
        res = nm.val()
        xray_frame = res['xraybase64']

        image = base64_to_pil(xray_frame)

        if image.mode != "RGB":
            image = image.convert("RGB")

        image = image.resize((224, 224))
        image = img_to_array(image)
        image /= 255
        image = np.expand_dims(image, axis=0)

        # Be careful how your trained model deals with the input
        # otherwise, it won't make correct prediction!

        preds = model.predict(image)

        pred_proba = "{:.3f}".format(np.amax(preds))  # Max probability
        pred_class = preds
        print(pred_proba)
        print(pred_class)
        if pred_class[0][0] >= 0.5:
            result = "Covid-19 tested positive. [Confidence ratio: " + str(
                round(pred_class[0][0] * 100, 2)) + "%]"
            # result += str(pred_class[0][0])
        else:
            result = "Covid-19 tested negative. [Confidence ratio: " + str(
                round((1 - pred_class[0][0]) * 100, 2)) + "%]"

            # result += str(pred_class[0][1])

        print(result)
        db.child("Appointments").child(user_index).update({"report": result})

        return (1)
def predict_image():

    print(request.files)

    imgData = request.files['image']

    img = Image.open(imgData)

    img = img.resize((150, 150))

    #print(imgData)

    # img = load_img(img, target_size=(150, 150))

    img = img_to_array(img)

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

    classes = str(model.predict_classes(img, batch_size=10))

    return classes
Exemple #15
0
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)

            # model = load_model('./animal_cnn_aug.h5')
            model = VGG16(weights='imagenet')
            image = Image.open(filepath)
            image = image.convert('RGB')
            image = image.resize((image_size, image_size))
            data = np.asarray(image)
            X = []
            X.append(data)
            X = np.array(X)

            result = model.predict([X])[0]
            predicted = result.argmax()
            percentage = int(result[predicted] * 100)

            return "ラベル: " + classes[predicted] + ", 確率:"+ str(percentage) + " %"




            # return redirect(url_for('uploaded_file',
            #                         filename=filename))
    return '''
Exemple #16
0
def app():
	new_model = keras.models.load_model("haemorrhage_modelnorm.h5")
	st.title("Hemorrhage Detection")
	st.markdown(hide_streamlit_style, unsafe_allow_html=True);
	
	uploaded_file_hem = st.file_uploader("Choose a image file", type=['png','jpg','jpeg'])
	if uploaded_file_hem is not None:
		image = Image.open(uploaded_file_hem)
		size =(128,128)
		image1=image.resize(size)
		image1=ImageOps.grayscale(image1)
		x=np.asarray(image1)
		x=np.expand_dims(x,axis=0)
		x=np.reshape(x,(1,128,128,1))
		x=x/255.0
		if(new_model.predict_classes(x)[0][0]==1):
			st.write('***Result: Hemorrhage***')
			with st.beta_expander('Show Image'):
				st.image(image,channels='BGR',width=200)
		else:
			st.write('***Result: Normal***')
			with st.beta_expander('Show Image'):
				st.image(image,channels='BGR',width=200)
Exemple #17
0
def make_prediction(base_model, top_model, image, filename):
    """

    """
    ## resize image
    image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT)).convert('RGB')
    image = np.asarray(image)

    ## pre-process
    image = image / 255
    image = np.expand_dims(image, axis=0)

    ## create bottleneck encoding
    bottleneck_prediction = base_model.predict(image)

    ## classify image
    predictions = top_model.predict(bottleneck_prediction)

    ## sort classes
    orders = predictions.argsort()[0]

    ## create prediction
    predicted_class = CLASSES_MAPPING[predictions.argmax(axis=1)[0]]
    
    ## create plot
    fig, ax = plt.subplots(figsize=(8,8))
    ax.barh(np.array(list(CLASSES_MAPPING.values()))[orders],predictions[0][orders], color="darkorange")
    ax.set_title("Prediction: " + predicted_class)
    for i, v in enumerate(predictions[0][orders]):
        if v>0.005:
            ax.text(v + 0.01, i - .2, "{:.0f}%".format(100*v), color='k', fontsize=15)
    ax.set_xlim(0, predictions[0].max()+0.15)
    ax.axes.xaxis.set_visible(False)
    plt.tight_layout()
    plt.savefig("./app/static/prediction/prediction_{}.png".format(filename), dpi=150)
    return predicted_class
Exemple #18
0
def organize_directories(df, class_dir, cap_count=None, test_size=0.2, random_state=42, test=False, verbose=True):
    """
    Organize the images into one directory for each class. This is meant to facilitate the use of 
    Keras ImageDataGenerator (flow from directory).

    Arguments:
        df: input dataframe containing the original image data
        class_dir: location to create the training and test directories
        cap_count: limit the number of samples per classes (if None, full set is used)
        test_size: fraction of the dataset to be used for the test set
        random_state: random_state to randomly split the data into training and test set
        test: if True, only 10% of the original images are considered (for debug only)
        verbose: if True, print progress

    Outputs:
        None
    """

    ## check if directory exists
    if cap_count:
        marker = "_" + str(cap_count)
    else:
        marker = ""
    if not os.path.exists(class_dir + marker):
        os.mkdir(class_dir + marker)

    ## create train/test directories
    if not os.path.exists(os.path.join(class_dir + marker, 'train')):
        os.mkdir(os.path.join(class_dir + marker, 'train'))
    if not os.path.exists(os.path.join(class_dir + marker, 'test')):
        os.mkdir(os.path.join(class_dir + marker, 'test'))

    ## TEST ONLY
    ## >>>>>>>>>>>>>>>>>>>>>
    ## split data
    if test:
        df, _ = train_test_split(df, test_size=0.1, random_state=random_state, stratify=df['style'])
    ## <<<<<<<<<<<<<<<<<<<<<

    ## create train and test sets
    X_train, X_test = train_test_split(df, test_size=test_size, random_state=random_state, stratify=df['style'])

    ## fill each directory with images
    for name, X in {'train':X_train, 'test':X_test}.items():
        ## create a folder for each class
        for s in X['style'].unique().tolist():
            if not os.path.exists(os.path.join(class_dir + marker, name, s)):
                os.mkdir(os.path.join(class_dir + marker, name, s))

        ## loop over each row of the dataframe and move image based on class
        counter = 0
        if verbose: print("... moving images")
        for index, row in X.iterrows():
        
            ## check if original image exists
            if not os.path.exists(row['file_loc']):
                continue
            
            ## check if number of items exceeds cap_count
            if cap_count:
                if name == "test":
                    count = int(test_size * cap_count)
                else:
                    count = int(cap_count)
            else:
                count = None
            if count:
                number_files = len(os.listdir(os.path.join(class_dir + marker, name, row['style'])))
                if number_files >= count:
                    continue

            ## create destination path
            destination = os.path.join(class_dir + marker, name, row['style'],str(row['content_id'])+'.png')

            ## read image
            image = Image.open(row['file_loc'])

            ## resize image
            new_image = image.resize((224, 224))

            ## save image
            new_image.convert('RGB').save(destination)
            counter+=1

        if verbose: print("... transfer completed.")
        print("{0}/{1} image found".format(counter, X.shape[0]))
Exemple #19
0
    img_path = os.path.join(img_dir, image_info['file_name'])
    # print(img_path)
    orig_images = [] # Store the images here.
    input_images = [] # Store resized versions of the images here.

    orig_images.append(imread(img_path))
    
    
    # keras preprocess
    # img = image.load_img(img_path, target_size=(image_size[0], image_size[1]))
    # img = image.img_to_array(img)
    # input_images.append(img)
    
    # tf preprocess
    image = Image.open(img_path)
    image = image.resize((image_size[0],image_size[1]),Image.ANTIALIAS)
    image_np = load_image_into_numpy_array(image)
    input_images.append(image_np)


    input_images = np.array(input_images,dtype=np.float32)

    input_images = input_images*(2.0 / 255.0)-1.0

    y_pred = model.predict(input_images)

    print("predict end.")

    confidence_threshold = confidence_thresh

    y_pred_thresh = [y_pred[k][y_pred[k,:,1] > confidence_threshold] for k in range(y_pred.shape[0])]