Spaces:
Runtime error
Runtime error
update
Browse files1234567891 unmodified line111213141516171819202122232425262728293012 unmodified lines4344454647484950515253545556575859606162631 unmodified line65666768697071727374757677787980818283848586878889909192939495961 unmodified line98991001011021031048 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import streamlit as stimport pandas as pdimport numpy as npfrom PIL import Image #Image Processingimport cv2 as cv2from matplotlib import pyplot as pltimport scipy.misc1 unmodified lineimport skimage.filtersimport sklearn.metricsimport imageioimport torchfrom model import AEScfrom postprocessing import postprocessing,final_predictionimport torchvision.transforms as TTfrom matplotlib.backends.backend_agg import FigureCanvasAgg12 unmodified linesPlease note that this application is intended to provide an estimate only and may not be accurate in all cases.""")#image uploaderimage = st.file_uploader(label = "Upload your image here",type=['png','jpg','jpeg'])def fat_choco_rateo(image, input_image, threshold):img = cv2.imread(image)original = cv2.imread(image)#convertion to gray scalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#threshold 160 set the rest to 255 (remove the border)ret, thresh = cv2.threshold(gray, 160, 255, cv2.THRESH_BINARY)1 unmodified lineimg[thresh == 255] = 0#core transformation#The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground objectkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))# A set of operations that process images based on shapes. Morphological operations apply a structuring element to an input image and generate an output image.erosion = cv2.erode(img, kernel, iterations = 1)#Return a contiguous flattened array.hist_analisy = erosion.ravel()#remove black coloro as we don't need to count themhist_analisy = [i for i in hist_analisy if i != 0]#count the pixelfat, choco = [], []for x in hist_analisy:(choco, fat)[int(x > threshold)].append(x)#semantic partmedian_filtered = scipy.ndimage.median_filter(img, size=3)predicted = np.uint8(median_filtered > threshold) * 255# Display results in Streamlitcol1, col2, col3, col4 = st.columns([1, 1, 1, 1])with col1:st.image(original, caption="Original", use_column_width=True)1 unmodified linest.image(img, caption="Detected Tortina", use_column_width=True)with col3:st.image(predicted, caption="Predicted bloom zone", use_column_width=True)with col4:fig, ax = plt.subplots(figsize=(6, 4))8 unmodified lineshist_image = np.asarray(buf)hist_image = cv2.resize(hist_image, (600, 600))st.image(hist_image, caption="Histogram", use_column_width=True)st.write("Percentuale fat")st.write( int( len (fat) / len(hist_analisy) * 100 ))st.write("Percentuale choco")st.write( int( len (choco) / len(hist_analisy) * 100))def auto_encoder_prediction(image,thresh):img = cv2.imread(image)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = cv2.resize(img, (256,256))img = np.expand_dims(img,(0))input = torch.tensor(img) #create a tensorX = input.permute( (0,3,1,2))X = TT.Grayscale()(X).float()/255 #convert it to grayscalegray = X.permute( (0,2,3,1)).numpy()[0]checkpoint = torch.load("./model/20230302-021129_tortina.pt", map_location="cpu")model = AESc(cmap="gray")model.load_state_dict(checkpoint["model_state_dict"])model.eval()Y = model(X)anomaly_maps = (Y - X).abs()anomaly_maps_np = anomaly_maps.permute((0,2,3,1)).detach().numpy()thresholded_anomaly_maps = (anomaly_maps_np > thresh).astype(np.uint8).max(-1)postprocessed_anomaly_maps = np.zeros_like(thresholded_anomaly_maps)postprocessed_anomaly_maps = postprocessing(gray, thresholded_anomaly_maps[0])predicted_area = final_prediction(anomaly_maps_np[0], postprocessed_anomaly_maps)[0]final_predictions = predicted_areargb_output = np.zeros( (postprocessed_anomaly_maps.shape) + (3,) )rgb_output[postprocessed_anomaly_maps == 1] = np.array([128/255,0,0])rgb_output[postprocessed_anomaly_maps == 2] = np.array([1,1,1])st.image(rgb_output, caption="rgb out", use_column_width=True)st.write( "Finale prediction: ", final_predictions )if image is not None:input_image = Image.open(image) #read imageimage = input_image.save("img.jpg")st.title('Histogram Approach')# Create a slider for the threshold valuethreshold = st.slider('Threshold (53 is the optimal value for Dark Tortinas)', 1 , 255 , 53)fat_choco_rateo("img.jpg",input_image , threshold)st.title('Deep Learning Approach')threshold2 = st.slider('Threshold (53 is the optimal value for Dark Tortinas)', 0.000 , 1.000 , 0.033)auto_encoder_prediction("img.jpg",threshold2)else:st.write("Upload an Image")st.caption("Made with ❤️ by @Sottovia Alessandro.")12345671 unmodified line910111213141516171812 unmodified lines3132333435363738394041424344454647484950511 unmodified line5354555657585960616263646566676869707172737475767778798081821 unmodified line84858687888990918 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import streamlit as stimport pandas as pdimport numpy as npfrom PIL import Image # Image Processingimport cv2 as cv2from matplotlib import pyplot as pltimport scipy.misc1 unmodified lineimport skimage.filtersimport sklearn.metricsimport imageioimport torchfrom model import AEScfrom postprocessing import postprocessing, final_predictionimport torchvision.transforms as TTfrom matplotlib.backends.backend_agg import FigureCanvasAgg12 unmodified linesPlease note that this application is intended to provide an estimate only and may not be accurate in all cases.""")#image uploaderimage = st.file_uploader(label="Upload your image here",type=['png', 'jpg', 'jpeg'])def fat_choco_rateo(image, input_image, threshold):img = cv2.imread(image)original = cv2.imread(image)#convertion to gray scalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#threshold 160 set the rest to 255 (remove the border)ret, thresh = cv2.threshold(gray, 160, 255, cv2.THRESH_BINARY)1 unmodified lineimg[thresh == 255] = 0#core transformation#The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground objectkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))# A set of operations that process images based on shapes. Morphological operations apply a structuring element to an input image and generate an output image.erosion = cv2.erode(img, kernel, iterations=1)#Return a contiguous flattened array.hist_analisy = erosion.ravel()#remove black coloro as we don't need to count themhist_analisy = [i for i in hist_analisy if i != 0]#count the pixelfat, choco = [], []for x in hist_analisy:(choco, fat)[int(x > threshold)].append(x)#semantic partmedian_filtered = scipy.ndimage.median_filter(img, size=3)predicted = np.uint8(median_filtered > threshold) * 255# Display results in Streamlitcol1, col2, col3, col4 = st.columns([1, 1, 1, 1])with col1:st.image(original, caption="Original", use_column_width=True)1 unmodified linest.image(img, caption="Detected Tortina", use_column_width=True)with col3:st.image(predicted, caption="Predicted bloom zone",use_column_width=True)with col4:fig, ax = plt.subplots(figsize=(6, 4))8 unmodified lineshist_image = np.asarray(buf)hist_image = cv2.resize(hist_image, (600, 600))st.image(hist_image, caption="Histogram", use_column_width=True)st.write("Percentuale fat")st.write(int(len(fat) / len(hist_analisy) * 100))st.write("Percentuale choco")st.write(int(len(choco) / len(hist_analisy) * 100))fat = (len(fat) / len(hist_analisy))#Define class appartenenceif( fat == 0):st.write("Class 0 ")if( fat > 0 and fat < 0.25):st.write("Class 1 ")if( fat >= 0.25 and fat < 0.50):st.write("Class 2 ")if( fat >= 50 and fat < 0.75):st.write("Class 3 ")if( fat >= 75 ):st.write("Class 4 ")def auto_encoder_prediction(image, thresh):img = cv2.imread(image)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = cv2.resize(img, (256, 256))img = np.expand_dims(img, (0))input = torch.tensor(img) # create a tensorX = input.permute((0, 3, 1, 2))X = TT.Grayscale()(X).float()/255 # convert it to grayscalegray = X.permute((0, 2, 3, 1)).numpy()[0]checkpoint = torch.load("./model/20230302-021129_tortina.pt", map_location="cpu")model = AESc(cmap="gray")model.load_state_dict(checkpoint["model_state_dict"])model.eval()Y = model(X)anomaly_maps = (Y - X).abs()anomaly_maps_np = anomaly_maps.permute((0, 2, 3, 1)).detach().numpy()thresholded_anomaly_maps = (anomaly_maps_np > thresh).astype(np.uint8).max(-1)postprocessed_anomaly_maps = np.zeros_like(thresholded_anomaly_maps)postprocessed_anomaly_maps = postprocessing(gray, thresholded_anomaly_maps[0])predicted_area = final_prediction(anomaly_maps_np[0], postprocessed_anomaly_maps)[0]final_predictions = predicted_areargb_output = np.zeros((postprocessed_anomaly_maps.shape) + (3,))rgb_output[postprocessed_anomaly_maps == 1] = np.array([128/255, 0, 0])rgb_output[postprocessed_anomaly_maps == 2] = np.array([1, 1, 1])st.image(rgb_output, caption="rgb out", use_column_width=True)st.write("Final class prediction: ", final_predictions)if image is not None:input_image = Image.open(image) # read imageimage = input_image.save("img.jpg")st.title('Histogram Approach')# Create a slider for the threshold valuethreshold = st.slider('Threshold (53 is the optimal value for Dark Tortinas)', 1, 255, 53)fat_choco_rateo("img.jpg", input_image, threshold)st.title('Deep Learning Approach')threshold2 = st.slider('Threshold (0.33 is the optimal value evalueted by the model)', 0.001, 1.000, 0.033)auto_encoder_prediction("img.jpg", threshold2)else:st.write("Upload an Image")st.caption("Made with ❤️ by @Sottovia Alessandro.")
app.py+80-88