Skip to content

Commit 93fe9a8

Browse files
committed
add code
1 parent 9d8fe5f commit 93fe9a8

File tree

7 files changed

+10447
-2
lines changed

7 files changed

+10447
-2
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/public/web_model/*
2+
13
# Logs
24
logs
35
*.log

README.md

100644100755
Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,68 @@
1-
# object-detection-react-app
2-
Real-Time Custom Object Detection with TensorFlow.js
1+
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2+
3+
## Available Scripts
4+
5+
In the project directory, you can run:
6+
7+
### `npm start`
8+
9+
Runs the app in the development mode.<br>
10+
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11+
12+
The page will reload if you make edits.<br>
13+
You will also see any lint errors in the console.
14+
15+
### `npm test`
16+
17+
Launches the test runner in the interactive watch mode.<br>
18+
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19+
20+
### `npm run build`
21+
22+
Builds the app for production to the `build` folder.<br>
23+
It correctly bundles React in production mode and optimizes the build for the best performance.
24+
25+
The build is minified and the filenames include the hashes.<br>
26+
Your app is ready to be deployed!
27+
28+
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29+
30+
### `npm run eject`
31+
32+
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33+
34+
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35+
36+
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37+
38+
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39+
40+
## Learn More
41+
42+
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43+
44+
To learn React, check out the [React documentation](https://reactjs.org/).
45+
46+
### Code Splitting
47+
48+
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49+
50+
### Analyzing the Bundle Size
51+
52+
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53+
54+
### Making a Progressive Web App
55+
56+
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57+
58+
### Advanced Configuration
59+
60+
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61+
62+
### Deployment
63+
64+
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65+
66+
### `npm run build` fails to minify
67+
68+
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

package.json

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"name": "tensorflowjs-object-detection",
3+
"version": "1.0.0",
4+
"description": "",
5+
"keywords": [],
6+
"main": "src/index.js",
7+
"dependencies": {
8+
"@tensorflow-models/coco-ssd": "0.1.1",
9+
"@tensorflow/tfjs": "0.14.0",
10+
"react": "16.5.2",
11+
"react-dom": "16.5.2",
12+
"react-magic-dropzone": "1.0.1",
13+
"react-scripts": "2.0.3"
14+
},
15+
"devDependencies": {},
16+
"scripts": {
17+
"start": "react-scripts start",
18+
"build": "react-scripts build",
19+
"test": "react-scripts test --env=jsdom",
20+
"eject": "react-scripts eject"
21+
},
22+
"browserslist": [">0.2%", "not dead", "not ie <= 11", "not op_mini all"]
23+
}

public/index.html

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="utf-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
7+
<meta name="theme-color" content="#000000">
8+
<!--
9+
manifest.json provides metadata used when your web app is added to the
10+
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
11+
-->
12+
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
13+
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
14+
<!--
15+
Notice the use of %PUBLIC_URL% in the tags above.
16+
It will be replaced with the URL of the `public` folder during the build.
17+
Only files inside the `public` folder can be referenced from the HTML.
18+
19+
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
20+
work correctly both with client-side routing and a non-root public URL.
21+
Learn how to configure a non-root public URL by running `npm run build`.
22+
-->
23+
<title>React App</title>
24+
</head>
25+
26+
<body>
27+
<noscript>
28+
You need to enable JavaScript to run this app.
29+
</noscript>
30+
<div id="root"></div>
31+
<!--
32+
This HTML file is a template.
33+
If you open it directly in the browser, you will see an empty page.
34+
35+
You can add webfonts, meta tags, or analytics to this file.
36+
The build step will place the bundled scripts into the <body> tag.
37+
38+
To begin the development, run `npm start` or `yarn start`.
39+
To create a production bundle, use `npm run build` or `yarn build`.
40+
-->
41+
</body>
42+
43+
</html>

src/index.js

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
import React from 'react'
2+
import ReactDOM from 'react-dom'
3+
import MagicDropzone from 'react-magic-dropzone'
4+
5+
import * as tf from '@tensorflow/tfjs'
6+
import './styles.css'
7+
8+
const MODEL_URL = './web_model/tensorflowjs_model.pb'
9+
const WEIGHTS_URL = './web_model/weights_manifest.json'
10+
11+
class App extends React.Component {
12+
state = {
13+
model: null,
14+
preview: '',
15+
predictions: []
16+
}
17+
18+
componentDidMount() {
19+
tf.loadFrozenModel(MODEL_URL, WEIGHTS_URL).then(model => {
20+
this.setState({
21+
model: model
22+
})
23+
})
24+
}
25+
26+
onDrop = (accepted, rejected, links) => {
27+
this.setState({ preview: accepted[0].preview || links[0] })
28+
}
29+
30+
cropToCanvas = (image, canvas, ctx) => {
31+
const naturalWidth = image.naturalWidth
32+
const naturalHeight = image.naturalHeight
33+
34+
canvas.width = image.width
35+
canvas.height = image.height
36+
37+
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
38+
if (naturalWidth > naturalHeight) {
39+
ctx.drawImage(
40+
image,
41+
(naturalWidth - naturalHeight) / 2,
42+
0,
43+
naturalHeight,
44+
naturalHeight,
45+
0,
46+
0,
47+
ctx.canvas.width,
48+
ctx.canvas.height
49+
)
50+
} else {
51+
ctx.drawImage(
52+
image,
53+
0,
54+
(naturalHeight - naturalWidth) / 2,
55+
naturalWidth,
56+
naturalWidth,
57+
0,
58+
0,
59+
ctx.canvas.width,
60+
ctx.canvas.height
61+
)
62+
}
63+
}
64+
65+
onImageChange = e => {
66+
const c = document.getElementById('canvas')
67+
const ctx = c.getContext('2d')
68+
this.cropToCanvas(e.target, c, ctx)
69+
70+
const batched = tf.tidy(() => {
71+
const img = tf.fromPixels(c)
72+
// Reshape to a single-element batch so we can pass it to executeAsync.
73+
return img.expandDims(0)
74+
})
75+
76+
const height = batched.shape[1]
77+
const width = batched.shape[2]
78+
79+
this.state.model.executeAsync(batched).then(result => {
80+
const boxes = result[0].dataSync()
81+
const scores = result[1].dataSync()
82+
const labels = result[2].dataSync()
83+
84+
// clean the webgl tensors
85+
batched.dispose()
86+
tf.dispose(result)
87+
88+
const prevBackend = tf.getBackend()
89+
// run post process in cpu
90+
tf.setBackend('cpu')
91+
const indexTensor = tf.tidy(() => {
92+
const boxes2 = tf.tensor2d(boxes, [
93+
result[0].shape[1],
94+
result[0].shape[2]
95+
])
96+
return tf.image.nonMaxSuppression(
97+
boxes2,
98+
scores,
99+
20, // maxNumBoxes
100+
0.5, // iou_threshold
101+
0.5 // score_threshold
102+
)
103+
})
104+
const indexes = indexTensor.dataSync()
105+
indexTensor.dispose()
106+
// restore previous backend
107+
tf.setBackend(prevBackend)
108+
109+
const predictions = this.buildDetectedObjects(
110+
width,
111+
height,
112+
boxes,
113+
scores,
114+
indexes,
115+
labels
116+
)
117+
118+
// Font options.
119+
const font = '16px sans-serif'
120+
ctx.font = font
121+
ctx.textBaseline = 'top'
122+
123+
predictions.forEach(prediction => {
124+
const x = prediction.bbox[0]
125+
const y = prediction.bbox[1]
126+
const width = prediction.bbox[2]
127+
const height = prediction.bbox[3]
128+
// Draw the bounding box.
129+
ctx.strokeStyle = '#00FFFF'
130+
ctx.lineWidth = 4
131+
ctx.strokeRect(x, y, width, height)
132+
// Draw the label background.
133+
ctx.fillStyle = '#00FFFF'
134+
const textWidth = ctx.measureText(prediction.class).width
135+
const textHeight = parseInt(font, 10) // base 10
136+
ctx.fillRect(x, y, textWidth + 4, textHeight + 4)
137+
})
138+
139+
predictions.forEach(prediction => {
140+
const x = prediction.bbox[0]
141+
const y = prediction.bbox[1]
142+
// Draw the text last to ensure it's on top.
143+
ctx.fillStyle = '#000000'
144+
ctx.fillText(prediction.class, x, y)
145+
})
146+
})
147+
}
148+
149+
buildDetectedObjects = (width, height, boxes, scores, indexes, classes) => {
150+
const count = indexes.length
151+
const objects = []
152+
for (let i = 0; i < count; i++) {
153+
const bbox = []
154+
for (let j = 0; j < 4; j++) {
155+
bbox[j] = boxes[indexes[i] * 4 + j]
156+
}
157+
const minY = bbox[0] * height
158+
const minX = bbox[1] * width
159+
const maxY = bbox[2] * height
160+
const maxX = bbox[3] * width
161+
bbox[0] = minX
162+
bbox[1] = minY
163+
bbox[2] = maxX - minX
164+
bbox[3] = maxY - minY
165+
objects.push({
166+
bbox: bbox,
167+
class: classes[indexes[i]],
168+
score: scores[indexes[i]]
169+
})
170+
}
171+
return objects
172+
}
173+
174+
render() {
175+
return (
176+
<div className="Dropzone-page">
177+
{this.state.model ? (
178+
<MagicDropzone
179+
className="Dropzone"
180+
accept="image/jpeg, image/png, .jpg, .jpeg, .png"
181+
multiple={false}
182+
onDrop={this.onDrop}
183+
>
184+
{this.state.preview ? (
185+
<img
186+
alt="upload preview"
187+
onLoad={this.onImageChange}
188+
className="Dropzone-img"
189+
src={this.state.preview}
190+
/>
191+
) : (
192+
'Choose or drop a file.'
193+
)}
194+
<canvas id="canvas" />
195+
</MagicDropzone>
196+
) : (
197+
<div className="Dropzone">Loading model...</div>
198+
)}
199+
</div>
200+
)
201+
}
202+
}
203+
204+
const rootElement = document.getElementById('root')
205+
ReactDOM.render(<App />, rootElement)

0 commit comments

Comments
 (0)