Thursday, 21 January 2021
Wednesday, 20 January 2021
keras 14 tensorflowjs mobileNet & ionic react 2
project site: http://chuanshuoge-ionic-tensorflowjs-mobilenet.surge.sh
//tensorflow_mobileNet.js
open website on phone browser, browse local image
press predict, start calculating prediction result
predicted a soccer ball
predicted a basketball
open browser on desktop -> browser a goose image ->
copy paste image url -> predict
mobileNet distinguish duck from goose
import React, { useState, useEffect } from 'react';
import * as tf from '@tensorflow/tfjs'
import imagenet_label from './imagenet_label.json'
import '../pages/Home.css';
import domtoimage from 'dom-to-image';
export default function MobileNet(props) {
const [model, setModel] = useState(null)
const [model_predictions, setModel_predictions] = useState(null)
useEffect(() => { loadModel() }, [props.predict]);
const loadModel = async () => {
const m = await tf.loadLayersModel('/assets/model.json')
setModel(m)
if (props.predict > 0) {
setModel_predictions(null)
//convert media to png before processing image
domtoimage.toPng(props.image)
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
//wait for new png image
var timer = setInterval(function () {
if (img.src) {
processImage(img)
clearInterval(timer)
}
}, 100)
})
.catch(function (error) {
alert("error converting image to png");
});
}
}
const processImage = async (image) => {
const pixels = tf.browser.fromPixels(image).resizeNearestNeighbor([224, 224]).toFloat()
const offset = tf.scalar(127.5)
const preprocessed_image = pixels.sub(offset).div(offset).expandDims()
const predictions = await model.predict(preprocessed_image).data()
//predictions is Float32Array(1000), find top5 value with their index
let top5 = []
for (let i = 0; i < 5; i++) {
const imax = predictions.indexOf(Math.max(...predictions));
const key = imagenet_label[imax.toString()]
const value = predictions[imax].toExponential(2).toString()
top5.push(<tr key={key}>
<td>{key}</td>
<td>{value}</td>
</tr>)
predictions[imax] = 0
}
/*top5
Array(5)
0: Object { "bald eagle, American eagle, Haliaeetus leucocephalus": "9.60e-1" }
1: Object { kite: "3.93e-2" }
2: Object { "black grouse": "9.76e-5" }
3: Object { vulture: "8.26e-5" }
4: Object { "black stork, Ciconia nigra": "7.81e-5" }
*/
setModel_predictions(top5)
}
return (
<div>
{props.predict > 0 && !model_predictions ? <span>Calculating...</span> : null}
{model_predictions ?
<table>
<thead><tr><th>Object</th><th>Probability</th></tr></thead>
<tbody>{model_predictions}</tbody>
</table> : null}
</div>
)
}
------------------------------
//home.tsx
import {
IonContent, IonHeader, IonPage, IonTitle, IonToolbar,
IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle,
IonItem, IonIcon, IonLabel, IonButton, IonInput
} from '@ionic/react';
import React, { useState } from 'react';
import './Home.css';
import MobileNet from '../components/tensorflow_mobileNet'
const Home: React.FC = () => {
const [predictClick, setPredictClick] = useState(0);
const [imageUrl, setImageUrl] = useState('https://images.theconversation.com/files/308043/original/file-20191220-11924-iakhpb.jpeg?ixlib=rb-1.1.0&q=45&auto=format&w=754&fit=clip')
const browseImg = (e: any) => {
const fileURL = URL.createObjectURL(e.target.files[0])
//get url where uploaded image is temporarily stored
//blob:http://localhost:3000/11c28a94-d9df-43e1-ab6c-2185e1449eb6
setImageUrl(fileURL)
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>
Predict Image with MobileNet
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<IonCard>
<IonCardHeader>
<IonCardTitle>
MobileNet Input Image
</IonCardTitle>
</IonCardHeader>
<IonItem lines="none">
<IonButton fill="outline"
onClick={() => document.getElementById('input-image-browser')?.click()}>
Browse Local Image</IonButton>
<input hidden type="file" accept="image/*" id="input-image-browser"
onChange={(e) => browseImg(e)}></input>
</IonItem>
<IonItem >
<IonLabel slot="start">Paste Web Image URL</IonLabel>
<IonInput type="url" placeholder="https://image.com/image.jpg"
onIonChange={(e) => setImageUrl(e.detail.value!)}></IonInput>
</IonItem>
<IonItem lines="none">
<img id='test_image' src={imageUrl} alt="Input Image"></img>
</IonItem>
<IonItem lines="none">
<IonButton fill="outline" onClick={() => setPredictClick(predictClick + 1)}>Predict</IonButton>
</IonItem>
<IonCardHeader>
<IonCardTitle>
MobileNet Prediction Result
</IonCardTitle>
</IonCardHeader>
<IonItem lines="none">
<MobileNet image={document.getElementById('test_image')} predict={predictClick} />
</IonItem>
</IonCard>
</IonContent>
</IonPage>
);
};
export default Home;
------------------------------
//package.json
{
"name": "ionic-keras",
"version": "0.0.1",
"private": true,
"dependencies": {
"@capacitor/core": "2.4.6",
"@ionic/react": "^5.0.7",
"@ionic/react-router": "^5.0.7",
"@tensorflow/tfjs": "^2.8.4",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^8.0.3",
"@types/jest": "^24.0.25",
"@types/node": "^12.12.24",
"@types/react": "^16.9.17",
"@types/react-dom": "^16.9.4",
"@types/react-router": "^5.1.4",
"@types/react-router-dom": "^5.1.3",
"dom-to-image": "^2.6.0",
"ionicons": "^5.0.0",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.0",
"typescript": "3.8.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@capacitor/cli": "2.4.6"
},
"description": "An Ionic project"
}
reference:
Tuesday, 19 January 2021
keras 13 tensorflowjs mobileNet & ionic react
create a python project to convert mobileNet model for tensorflowjs
#powershellpip install tensorflow
pip install tensorflowjs
#main.py
#main.py
import tensorflowjs as tfjs
import tensorflow as tf
mobileNet = tf.keras.applications.mobilenet.MobileNet()
tfjs.converters.save_keras_model(mobileNet,'mobileNet')
create ionic react project,
copy paste model generated from python project into public/assets folder
//cmd
ionic start app-name
npm install @tensorflow/tfjs
npm install dom-to-image
reference:
load tensorflowjs model by javascript
tf.fromPixels was deprecated
react serve static files
imagenet labels
dom to image - media source unsecure error
get temporary url for browsed local image
Sunday, 17 January 2021
keras 12 vgg16 & django
code link: https://github.com/chuanshuoge6/keras-vgg16
copy paste web image url, click submit
copy paste another web image url
browse image on computer
#views.py
import os
from django.shortcuts import render
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications import imagenet_utils
import numpy as np
import urllib.request
# Create your views here.
def index(request):
return render(request, 'index.html')
def local_image(request):
image_file = request.FILES['image_file']
with open('static/static-image.jpg', 'wb') as f:
for chunk in image_file.chunks():
f.write(chunk)
prediction = predict_image('static/static-image.jpg')
return render(request, 'index.html', {'prediction': prediction, "local_image_file": image_file})
def web_image(request):
image_file = request.POST['image_file']
urllib.request.urlretrieve(image_file, "static/static-image.jpg")
prediction = predict_image('static/static-image.jpg')
return render(request, 'index.html', {'prediction': prediction, "web_image_file": image_file})
def predict_image(file):
# run on cpu
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
vgg16 = tf.keras.applications.vgg16.VGG16()
img = image.load_img(file, target_size=(224, 224))
img_array = image.img_to_array(img)
img_array_expanded_dims = np.expand_dims(img_array, axis=0)
preprocessed_image = tf.keras.applications.vgg16.preprocess_input(img_array_expanded_dims)
predictions = vgg16.predict(preprocessed_image)
return imagenet_utils.decode_predictions(predictions)[0]
-----------------------
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VGG16</title>
<style>
table, th, td {
border: 1px solid black;
}
tr:nth-child(even) {background-color: #f2f2f2;}
th, td {padding: 10px;}
img{height: 300px; width: 300px}
</style>
</head>
<body>
<h2>Predict Image with VGG16</h2>
<h4>Select local image</h4>
<form action="{% url 'local_image' %}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<input type="file" accept="image/*" name="image_file" id="local_image_file" onchange="local_image_change()">
<input type="submit" id="submit_button" style="display:none">
</form>
<h4>Copy web image url</h4>
<form action="{% url 'web_image' %}" method="post">
{% csrf_token %}
{% if web_image_file %}
<input name="image_file" type="url" id="web_image_url"
value={{web_image_file}}
onchange="web_image_change()">
{% else %}
<input name="image_file" type="url" id="web_image_url2"
value="https://images.theconversation.com/files/308043/original/file-20191220-11924-iakhpb.jpeg?ixlib=rb-1.1.0&q=45&auto=format&w=754&fit=clip"
onchange="web_image_change2()">
{% endif %}
<input type="submit" >
</form>
<h4>VGG16 input image</h4>
{% if local_image_file %}
{% load static %}
<img id="selected_image3" src="{% static 'static-image.jpg' %}">
{% elif web_image_file %}
<img id="selected_image" src="{{web_image_file}}">
{% else %}
{% load static %}
<img id="selected_image2" src="{% static 'spider.jpg' %}">
{% endif %}
<h4>VGG16 Prediction Result</h4>
<table>
<tr>
<th>Object</th>
<th>Probability</th>
</tr>
{% for row in prediction %}
<tr>
{% for col in row %}
{% if forloop.counter != 1 %}
<td>{{ col|safe }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
<script>
function local_image_change(){
var img_input = document.getElementById("local_image_file")
try{document.getElementById("selected_image2").src = URL.createObjectURL(img_input.files[0])}catch(err){}
try{document.getElementById("selected_image3").src = URL.createObjectURL(img_input.files[0])}catch(err){}
document.getElementById("submit_button").click()
}
function web_image_change(){
document.getElementById("selected_image").src = document.getElementById("web_image_url").value
}
function web_image_change2(){
document.getElementById("selected_image2").src = document.getElementById("web_image_url2").value
}
</script>
</body>
</html>
-----------------------------------
#urls.py
from django.contrib import admin
from django.urls import path
from mobileNet import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('local_image/', views.local_image, name='local_image'),
path('web_image/', views.web_image, name='web_image'),
]
--------------------------------
#settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
-------------------------------
#powershell
pip install whitenoise gunicorn
pip freeze > requirements.txt
------------------------------
#requirements
absl-py==0.11.0
asgiref==3.3.1
astunparse==1.6.3
cachetools==4.2.0
certifi==2020.12.5
chardet==4.0.0
Django==3.1.5
django-watchman==1.2.0
flatbuffers==1.12
gast==0.3.3
google-auth==1.24.0
google-auth-oauthlib==0.4.2
google-pasta==0.2.0
grpcio==1.32.0
gunicorn==20.0.4
h5py==2.10.0
idna==2.10
joblib==1.0.0
Keras-Preprocessing==1.1.2
Markdown==3.3.3
numpy==1.19.5
oauthlib==3.1.0
opt-einsum==3.3.0
Pillow==8.1.0
protobuf==3.14.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pytz==2020.5
requests==2.25.1
requests-oauthlib==1.3.0
rsa==4.7
scikit-learn==0.24.0
six==1.15.0
sklearn==0.0
sqlparse==0.4.1
tensorboard==2.4.1
tensorboard-plugin-wit==1.7.0
tensorflow==2.4.0
tensorflow-estimator==2.4.0
termcolor==1.1.0
threadpoolctl==2.1.0
typing-extensions==3.7.4.3
urllib3==1.26.2
Werkzeug==1.0.1
whitenoise==5.2.0
wrapt==1.12.1
reference:
save web image to local
django template table
django serve static image
django multipart form file upload
python copy InMemoryUploadedFile object to disk
heroku deploy slug size too large
Compiled slug size: 526.6M is too large (max is 500M).
How to mirror phone display to pc?
download vysor
connect usb between phone and pc
enable usb debugging on phone
start vysor
control phone from pc with mouse
drag mouse on pc to switch screen on phone
reference:
Saturday, 16 January 2021
keras 11 mobileNet 2
mobileNet prediction
[[('n02510455', 'giant_panda', 0.9997156),
('n02509815', 'lesser_panda', 0.00016485745),
('n02447366', 'badger', 8.6640284e-05),
('n02445715', 'skunk', 1.2499775e-05),
('n02443114', 'polecat', 1.1246146e-05)]]
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, Dense, Flatten, Conv2D, MaxPool2D, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications import imagenet_utils
from sklearn.metrics import confusion_matrix
import itertools
import shutil
import random
import os
import glob
import matplotlib.pyplot as plt
from tensorflow.keras.models import load_model
import numpy as np
#train on GPU
pysical_devices = tf.config.experimental.list_physical_devices('GPU')
#print("Num GPUs Available: ", len(pysical_devices))
tf.config.experimental.set_memory_growth(pysical_devices[0], True)
mobile = tf.keras.applications.mobilenet.MobileNet()
def prepare_image(file):
img = image.load_img('data/' + file, target_size=(224, 224))
img_array = image.img_to_array(img)
img_array_expanded_dims = np.expand_dims(img_array, axis=0)
return tf.keras.applications.mobilenet.preprocess_input(img_array_expanded_dims)
preprocessed_image = prepare_image('panda.jpg')
predictions = mobile.predict(preprocessed_image)
results = imagenet_utils.decode_predictions(predictions)
print(results)
reference:
Subscribe to:
Posts (Atom)















