Skip to content

Commit

Permalink
Merge pull request #2 from Velvetklr/main
Browse files Browse the repository at this point in the history
Pull Request 2
  • Loading branch information
S-Bonillas authored Jan 30, 2024
2 parents bcfb6d8 + 3f8c60d commit d3fe902
Show file tree
Hide file tree
Showing 30 changed files with 1,924 additions and 4 deletions.
Binary file added .DS_Store
Binary file not shown.
962 changes: 962 additions & 0 deletions P4_MicroPystics v2.ipynb

Large diffs are not rendered by default.

64 changes: 60 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,62 @@
# P4_MicroPystics
![app_image](https://www.tetratech.com/wp-content/uploads/2023/10/Evaluating-the-Risk-of-Microplastics-in-Coastal-Waters-One-Water.jpg)

# Indisposable: Microplastic Detection and Avoidance
![MIT](https://img.shields.io/badge/License-MIT-C7F9CC)
![contributors](https://img.shields.io/badge/Contributors-5-38A3A5)


## Description
Using Machine Learning, Image Recognition, and Computer Vision to detect microplastics in water samples.

**Original Data Source:**
Microplastic Dataset for Computer Vision, MOHAMADREZA MOMENI
https://www.kaggle.com/datasets/imtkaggleteam/microplastic-dataset-for-computer-vision

## Table of Contents
- [Installation](#installation)
- [Data](#data)
- [License](#license)
- [Dashboard](#dashboard)
- [Presentation](#presentation)
- [Contact](#contact)


## Installation
The following need to be installed to successfully run the model and aPI.

|Google Colab | Flask API|
| :-----------|:---------|
| tensorflow |tensorflow|
| drive | Flask |
| numpy | numpy |
| os | os |
|skimage.color| Pillow |
| matplotlib | |
| sklearn | |
| MobileNetV2 | |


# Data

## Source Data
- #### [Microplastic Dataset for Computer Vision, MOHAMADREZA MOMENI](https://www.kaggle.com/datasets/imtkaggleteam/microplastic-dataset-for-computer-vision)
- #### [Organisation for Economic CO-Operation and Development](https://stats.oecd.org/viewhtml.aspx?datasetcode=PLASTIC_WASTE_5&lang=en)

# Results and evaluation


## License
MIT

## Dashboard
#### [Tableu Dashboard](https://public.tableau.com/app/profile/aspen.jack/viz/GlobalPlasticPollution2000-2019/FatesbyLocation)

## Presentation
#### [Microplastic Slides](https://docs.google.com/presentation/d/1sRxoyioXgtXuvYpZf2QyY2WqkmBYswgg-BXrIF9GpOc/edit#slide=id.gf1b017c262_0_97)

## Contact
If there are any questions or concerns, we can be reached at:
##### [github: aspenjack](https://github.com/aspenjack)
##### [github: arpitas0690](https://github.com/arpitas0690)
##### [github: S-Bonillas](https://github.com/S-Bonillas)
##### [github: Sequoiabm](https://github.com/Sequoiabm)
##### [github: velvetklr](https://github.com/velvetklr)


Binary file added Resources/.DS_Store
Binary file not shown.
Binary file added Resources/2_Validation/.DS_Store
Binary file not shown.
Binary file added Resources/3_Testing/.DS_Store
Binary file not shown.
105 changes: 105 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Create API of ML model using flask

# Import libraries
import os
from flask import Flask, render_template, request, url_for, redirect, flash, jsonify
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import img_to_array
from skimage.color import rgb2gray
from skimage.transform import resize
from PIL import Image
import numpy as np

# Create upload file path
upload_folder = "static/upload"
temp = "model/"

# Create an app
app = Flask(__name__,static_url_path='/static')
app.config['upload_folder'] = upload_folder
#app.config['UPLOAD_FOLDER'] = 'static/upload'


# Load the model
model = tf.keras.models.load_model("model/saved_model")




@app.route('/')
def home():
return render_template("index.html")

def preprocess_input_for_prediction(image_path):
image = load_img(image_path, target_size=(128, 128))
image_array = img_to_array(image)
image_array = preprocess_input(image_array)
image_array = np.expand_dims(image_array, axis=0)
return image_array

# return image_array
# def preprocess_image(image_path):
# # Read the image using OpenCV
# image = Image.open(image_path).convert("RGB")

# # print("Image Channels (PIL):", image.mode)
# # print("Image Shape (PIL):", np.array(image).shape)

# # Resize the image to (150, 150)
# image = tf.image.resize(image, (128, 128))

# # Convert the image to a NumPy array
# image_array = np.array(image)

# # Normalize the image
# image_array = image_array / 255.0 # Assuming pixel values are in the range [0, 255]

# image_array = np.transpose(image_array, (0, 1, 2))

# # Add batch dimension
# image_array = np.expand_dims(image_array, axis=0)

# image_tensor = tf.convert_to_tensor(image_array, dtype=tf.float32)

# return image_tensor

@app.route('/predict',methods=['POST'])
def predict():
# Get the data from the POST request.
if request.method == "POST":
if 'exp' not in request.files:
return 'No File!'
file = request.files['exp']

path = os.path.join("static/upload", file.filename)
#path = os.path.join(app.config['upload_folder'],file.filename)
file.save(path)

input_data = preprocess_input_for_prediction(path)

predictions = model.predict(input_data)
print("Raw Predictions:", predictions)

binary_predictions = (predictions > 0.5).astype(int)

class_predict = "Clean" if binary_predictions == 0 else "Microplastics"

result = {
"class_predict": class_predict,
"binary_predictions": binary_predictions.flatten().tolist(),
"predictions": predictions.flatten().tolist(),
"image_path": path
}

return render_template("results.html", image_path=path, class_predict=class_predict, binary_predictions=binary_predictions, predictions=predictions)
return jsonify(result)

#return render_template('index.html')

if __name__ == '__main__':
app.run(debug=True,port=5001)
Binary file added model/.DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions model/saved_model/fingerprint.pb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
��ѝ�����҈����)�ݏ���C �܂�я��(����ԬŞq2
304 changes: 304 additions & 0 deletions model/saved_model/keras_metadata.pb

Large diffs are not rendered by default.

Binary file added model/saved_model/saved_model.pb
Binary file not shown.
Binary file not shown.
Binary file added model/saved_model/variables/variables.index
Binary file not shown.
Binary file added model/saved_modelv1/.DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions model/saved_modelv1/fingerprint.pb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
⾷��򢟰�Ç�˻����������Π ���ޯ���^(����͍��2
304 changes: 304 additions & 0 deletions model/saved_modelv1/keras_metadata.pb

Large diffs are not rendered by default.

Binary file added model/saved_modelv1/saved_model.pb
Binary file not shown.
Binary file not shown.
Binary file added model/saved_modelv1/variables/variables.index
Binary file not shown.
Binary file added static/.DS_Store
Binary file not shown.
Binary file added static/Images/Fitz - Bottle.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/Images/Hands - Pencil 1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/Images/Lifesavers - Gel Soap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/Images/x-Clean-00021.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/Images/x-Clean-00063.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 52 additions & 0 deletions static/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* Center-align text using CSS */
body {
text-align: center;
color: #000000; /* Text color (you can use color names, hexadecimal, RGB, etc.) */
font-family: 'Roboto', sans-serif; /* Font family (fallback to sans-serif if Arial is not available) */
}

/* Create a container with a max-width to center content */
.container {
max-width: 1000px; /* Adjust as needed */
margin: 0 auto; /* Center the container */
padding: 20px; /* Add padding for spacing inside the container */
}

.styled-button {
background-color: #57CC99; /* Bright background color */
color: #ffffff; /* Text color */
padding: 15px 20px; /* Adjust padding for size */
font-size: 16px; /* Adjust font size */
border: none; /* Remove default border */
border-radius: 8px; /* Add rounded corners */
cursor: pointer; /* Add a pointer cursor on hover */
transition: background-color 0.3s ease; /* Smooth background color transition */
}

/* Create a box around text */
.boxed-text {
border: 2px solid #333; /* Border style, width, and color */
padding: 100px; /* Add padding for spacing inside the box */
display: inline-block; /* Make the box inline with the text */
}

/* Example of different text colors and fonts for specific elements */
h1 {
color: #22557A; /* Dark Blue text color for h1 */
font-family: 'Roboto', sans-serif; /* Font family for h1 */
}

h2 {
color: #38A3A5; /* Light Blue text color for h1 */
font-family: 'Roboto', sans-serif; /* Font family for h1 */
}

p.special-text {
color: #000000; /* Black text color for paragraphs with class 'special-text' */
font-family: 'Roboto Slab', sans-serif; /* Font family for paragraphs with class 'special-text' */
}

li.special-text {
color: #000000; /* Black text color for list text with class 'special-text' */
font-family: 'Roboto Slab', sans-serif; /* Font family for list line with class 'special-text' */
}
Binary file added static/upload/.DS_Store
Binary file not shown.
Binary file added templates/.DS_Store
Binary file not shown.
102 changes: 102 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<title>Does your water contain microplastics?</title>
</head>
<body>
<div class="container">

<br>
<h1>What are microplastics?</h1>
<h2>Microplastics are plastic debris that are less than 5 millimeters
in length (about the size of a pencil eraser)</h2>
<br>
<!-- Use the img element to insert an image -->
<img src="{{ url_for('static', filename='Images/Hands - Pencil 1.png') }}" alt="Pencil">
<br>
<h1>Where do microplastics come from?</h1>
<h2>Microplastics come from many sources, including from larger plastic
debris like plastic bottles that degrade into tiny pieces.
</h2>
<br>
<img src="{{ url_for('static', filename='Images/Fitz - Bottle.png') }}" alt="Plastic Bottle">
<h2>In addition, microbeads, a type of microplastic, are very tiny pieces of
manufactured polyethylene plastic that are added as exfoliants to health and
beauty products, such as some cleansers and toothpastes. These tiny particles
easily pass through water filtration systems and end up in the ocean and Great Lakes.</h2>
<br>
<img src="{{ url_for('static', filename='Images/Lifesavers - Gel Soap.png') }}" alt="Exfoliant">
<h1>Plastic pollution in oceans and rivers is a growing environmental hazard.
</h1>
<h2>Plastic is increasingly accumulating on riverbanks, deltas, coastlines, and on the ocean surface.
About 60% of all plastic ever made has been discarded in landfills or in the natural environment.</h2>

<br>
<div class='tableauPlaceholder' id='viz1706247168791' style='position: relative'><noscript>
<a href='#'><img alt=' ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Gl&#47;GlobalPlasticPollution2000-2019&#47;GlobalPlasticsStory&#47;1_rss.png' style='border: none' /></a>
</noscript>
<object class='tableauViz' style='display:none;'><param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' />
<param name='embed_code_version' value='3' />
<param name='site_root' value='' />
<param name='name' value='GlobalPlasticPollution2000-2019&#47;GlobalPlasticsStory' />
<param name='tabs' value='yes' /><param name='toolbar' value='yes' />
<param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Gl&#47;GlobalPlasticPollution2000-2019&#47;GlobalPlasticsStory&#47;1.png' />
<param name='animate_transition' value='yes' />
<param name='display_static_image' value='yes' />
<param name='display_spinner' value='yes' />
<param name='display_overlay' value='yes' />
<param name='display_count' value='yes' />
<param name='language' value='en-US' />
<param name='filter' value='publish=yes' />
</object>
</div>
<script type='text/javascript'>
var divElement = document.getElementById('viz1706247168791');
var vizElement = divElement.getElementsByTagName('object')[0];
vizElement.style.width='1016px';vizElement.style.height='1014px';
var scriptElement = document.createElement('script');
scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';
vizElement.parentNode.insertBefore(scriptElement, vizElement);
</script>
<br>
<span class="boxed-text">
<img src="https://media4.giphy.com/media/26FKUf6xaZnevRT5C/giphy.gif" alt="microplastics">
<h1>Does your water contain microplastics?</h1>
<h2>Upload your photo and find out!</h2>
<p class="special-text">Take a picture of your water, like this. Crop to 128 by 128 px</p>
<img src="{{ url_for('static', filename='Images/x-Clean-00063.jpg') }}" alt="Clean Water">
<br>
<br>
<form action="/predict" method="POST" enctype="multipart/form-data">
<div class="fieldset">
<br>
<input type="file" id="imageUpload" name="exp" accept=".jpg, .jpeg, .png" required>
<br>
</div>
<br>
<input type="submit" class="styled-button" value="Predict">
</form>
</span>



<h1>Sources</h1>

<ol>
<li class="special-text">M. Rochman, M. A. Browne, B. S. Halpern, B. T. Hentschel, E. Hoh, H. K. Karapanagioti, L. M. Rios-Mendoza, H. Takada, S. Teh, R. C. Thompson, Policy: Classify plastic waste as hazardous. Nature 494, 169–171 (2013).
</li>
<li class="special-text">L. Lavers, A. L. Bond, Exceptional and rapid accumulation of anthropogenic debris on one of the world's most remote and pristine islands. Proc. Natl. Acad. Sci. U.S.A. 114, 6052–6055 (2017).
</li>
<li class="special-text">Lebreton, B. Slat, F. Ferrari, B. Sainte-Rose, J. Aitken, R. Marthouse, S. Hajbane, S. Cunsolo, A. Schwarz, A. Levivier, K. Noble, P. Debeljak, H. Maral, R. Schoeneich-Argent, R. Brambini, J. Reisser, Evidence that the Great Pacific Garbage Patch is rapidly accumulating plastic. Sci. Rep. 8, 4666 (2018).
</li>
<li class="special-text">Geyer, J. R. Jambeck, K. L. Law, Production, use, and fate of all plastics ever made. Sci. Adv. 3, e1700782 (2017).
</li>
<li class="special-text">Lourens J. J. Meijer et al.,More than 1000 rivers account for 80% of global riverine plastic emissions into the ocean.Sci. Adv.7,eaaz5803(2021).DOI:10.1126/sciadv.aaz5803</li>
</ol>
</div>
</body>
</html>
33 changes: 33 additions & 0 deletions templates/results.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Results!</title>
<!-- bootstrap style sheet -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- OurCSS -->
<link rel="stylesheet" href="/P4_MicroPystics/static/style.css" />
</head>


<body style="background:#ffffff">
<div class="container">
<h1>Wow, Look at those Results!</h1>
<img src="{{ image_path }}" alt="Uploaded Image">

<h2> Prediction: </h2>
<p>{{ class_predict }}</p>

<h2> Binary </h2>
<p>{{ binary_predictions }}</p>

<h2> Raw </h2>
<p>{{ predictions }}</p>

<a href="{{ url_for('home') }}">Back to Home</a>

</div>

</body>
</html>

0 comments on commit d3fe902

Please sign in to comment.