Browse Source

Added examples

Change-Id: Id952e4ade28cdab226d8daab6865c951d476e1b7
Viswanath Kumar Skand Priya 6 months ago
parent
commit
2f791de40e

BIN
examples/KnowThyNumber/BE/files/grayscale.png View File


+ 0
- 0
examples/KnowThyNumber/BE/files/predict.png View File


BIN
examples/KnowThyNumber/BE/server View File


+ 17
- 0
examples/KnowThyNumber/BE/server.go View File

@@ -0,0 +1,17 @@
1
+package main
2
+
3
+import (
4
+	"net/http"
5
+)
6
+
7
+func ping(w http.ResponseWriter, r *http.Request) {
8
+	w.Write([]byte("pong"))
9
+}
10
+func main() {
11
+	http.Handle("/", http.FileServer(http.Dir("../FE")))
12
+	http.HandleFunc("/ping", ping)
13
+	http.HandleFunc("/upload/", UploadFile)
14
+	if err := http.ListenAndServe(":9000", nil); err != nil {
15
+		panic(err)
16
+	}
17
+}

+ 174
- 0
examples/KnowThyNumber/BE/upload.go View File

@@ -0,0 +1,174 @@
1
+package main
2
+
3
+import (
4
+	"bytes"
5
+	"fmt"
6
+	"image"
7
+	"image/color"
8
+	"image/png"
9
+	"io"
10
+	"io/ioutil"
11
+	"math"
12
+	"mime/multipart"
13
+	"net/http"
14
+	"os"
15
+
16
+	"github.com/disintegration/imaging"
17
+	"github.com/harrydb/go/img/grayscale"
18
+	// "github.com/nfnt/resize"
19
+)
20
+
21
+// UploadFile uploads a file to the server
22
+func UploadFile(w http.ResponseWriter, r *http.Request) {
23
+	fmt.Printf("Inside upload \n")
24
+	if r.Method != http.MethodPost {
25
+		http.Redirect(w, r, "/", http.StatusSeeOther)
26
+		return
27
+	}
28
+
29
+	// Save a copy of this request for debugging.
30
+	//requestDump, err := httputil.DumpRequest(r, true)
31
+	//if err != nil {
32
+	//	fmt.Println(err)
33
+	//}
34
+
35
+	//fmt.Println(string(requestDump))
36
+
37
+	file, handle, err := r.FormFile("file")
38
+	if err != nil {
39
+		fmt.Printf("upload error\n")
40
+		fmt.Println(err.Error())
41
+		fmt.Fprintf(w, "%v", err)
42
+		return
43
+	}
44
+	defer file.Close()
45
+
46
+	mimeType := handle.Header.Get("Content-Type")
47
+	switch mimeType {
48
+	// case "image/jpeg":
49
+	//	saveFile(w, file, handle)
50
+	case "image/png":
51
+		saveFile(w, file, handle)
52
+	default:
53
+		jsonResponse(w, http.StatusBadRequest, "The format file is not valid.")
54
+	}
55
+}
56
+
57
+func processImage(infile multipart.File) (err error) {
58
+	imgSrc, _, err := image.Decode(infile)
59
+	if err != nil {
60
+		panic(err.Error())
61
+	}
62
+
63
+	// Create a new grayscale image
64
+	bounds := imgSrc.Bounds()
65
+	w, h := bounds.Max.X, bounds.Max.Y
66
+	grayScale := image.NewGray(image.Rectangle{image.Point{0, 0}, image.Point{w, h}})
67
+	for x := 0; x < w; x++ {
68
+		for y := 0; y < h; y++ {
69
+			imageColor := imgSrc.At(x, y)
70
+			rr, gg, bb, _ := imageColor.RGBA()
71
+			r := math.Pow(float64(rr), 2.2)
72
+			g := math.Pow(float64(gg), 2.2)
73
+			b := math.Pow(float64(bb), 2.2)
74
+			m := math.Pow(0.2125*r+0.7154*g+0.0721*b, 1/2.2)
75
+			Y := uint16(m + 0.5)
76
+			grayColor := color.Gray{uint8(Y >> 8)}
77
+			grayScale.Set(x, y, grayColor)
78
+		}
79
+	}
80
+
81
+	//Resize image
82
+	newImg := imaging.Resize(imgSrc, 28, 28, imaging.Lanczos)
83
+
84
+	// Grayscale 2
85
+	grayImg := grayscale.Convert(newImg, grayscale.ToGrayLuminance)
86
+	threshold := grayscale.Otsu(grayImg)
87
+	grayscale.Threshold(grayImg, threshold, 0, 255)
88
+
89
+	// Encode the grayscale image to the new file
90
+	newFileName := "grayscale.png"
91
+	newfile, err := os.Create("./files/" + newFileName)
92
+	if err != nil {
93
+		fmt.Printf("failed creating %s: %s", newfile, err)
94
+		return err
95
+	}
96
+	//defer newfile.Close()
97
+	//png.Encode(newfile, grayScale)
98
+	png.Encode(newfile, grayImg)
99
+
100
+	return nil
101
+}
102
+
103
+func saveFile(w http.ResponseWriter, file multipart.File, handle *multipart.FileHeader) {
104
+	err := processImage(file)
105
+	//data, err := ioutil.ReadAll(file2)
106
+	if err != nil {
107
+		fmt.Fprintf(w, "%v", err)
108
+		fmt.Println("%v", err)
109
+		return
110
+	}
111
+
112
+	//err = ioutil.WriteFile("./files/"+handle.Filename, data, 0666)
113
+	//if err != nil {
114
+	//	fmt.Fprintf(w, "%v", err)
115
+	//	return
116
+	//}
117
+	resp := predictNumber()
118
+	jsonResponse(w, http.StatusCreated, resp)
119
+}
120
+
121
+func postFile(filename string, targetUrl string) (string, error) {
122
+	bodyBuf := &bytes.Buffer{}
123
+	bodyWriter := multipart.NewWriter(bodyBuf)
124
+
125
+	// this step is very important
126
+	fileWriter, err := bodyWriter.CreateFormFile("file", filename)
127
+	if err != nil {
128
+		fmt.Println("error writing to buffer")
129
+		return "", err
130
+	}
131
+
132
+	// open file handle
133
+	fh, err := os.Open(filename)
134
+	if err != nil {
135
+		fmt.Println("error opening file")
136
+		return "", err
137
+	}
138
+	defer fh.Close()
139
+
140
+	//iocopy
141
+	_, err = io.Copy(fileWriter, fh)
142
+	if err != nil {
143
+		return "", err
144
+	}
145
+
146
+	contentType := bodyWriter.FormDataContentType()
147
+	bodyWriter.Close()
148
+
149
+	resp, err := http.Post(targetUrl, contentType, bodyBuf)
150
+	if err != nil {
151
+		return "", err
152
+	}
153
+	defer resp.Body.Close()
154
+	resp_body, err := ioutil.ReadAll(resp.Body)
155
+	if err != nil {
156
+		return "", err
157
+	}
158
+	fmt.Println(resp.Status)
159
+	fmt.Println(string(resp_body))
160
+	return string(resp_body), nil
161
+}
162
+
163
+func predictNumber() string {
164
+	target_url := "http://localhost:5000/mnist/classify"
165
+	filename := "./files/grayscale.png"
166
+	resp, _ := postFile(filename, target_url)
167
+	return resp
168
+}
169
+
170
+func jsonResponse(w http.ResponseWriter, code int, message string) {
171
+	w.Header().Set("Content-Type", "application/json")
172
+	w.WriteHeader(code)
173
+	fmt.Fprint(w, message)
174
+}

+ 170
- 0
examples/KnowThyNumber/FE/JsCode.js View File

@@ -0,0 +1,170 @@
1
+var mousePressed = false;
2
+var lastX, lastY;
3
+var ctx, ctx2;
4
+
5
+function InitThis() {
6
+    ctx = document.getElementById('myCanvas').getContext("2d");
7
+    ctx2 = document.getElementById('myCanvas2').getContext("2d");
8
+
9
+    $('#myCanvas').mousedown(function (e) {
10
+        mousePressed = true;
11
+        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
12
+    });
13
+
14
+    $('#clear-area').mousedown(function (e) {
15
+        clearArea();
16
+    });
17
+
18
+    $('#upload-area').mousedown(function (e) {
19
+        //uploadArea2();
20
+    });
21
+
22
+    $('#myCanvas').mousemove(function (e) {
23
+        if (mousePressed) {
24
+            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
25
+        }
26
+    });
27
+
28
+    $('#myCanvas').mouseup(function (e) {
29
+        mousePressed = false;
30
+        //alert("mouseup")
31
+    });
32
+
33
+    $('#myCanvas').mouseleave(function (e) {
34
+        mousePressed = false;
35
+        //alert("mouseleave")
36
+    });
37
+
38
+    document.addEventListener('touchstart',function(e){ mapTouchEvents(e,'mousedown'); },true);
39
+    document.addEventListener('touchmove',function(e){ mapTouchEvents(e,'mousemove'); },true);
40
+    document.addEventListener('touchend',function(e){ mapTouchEvents(e,'mouseup'); },true);
41
+    document.addEventListener('touchcancel',function(e){ mapTouchEvents(e,'mouseup'); },true);
42
+
43
+}
44
+
45
+function uploadArea() {
46
+    alert('Inside Upload....');
47
+    console.log("Inside Upload....");
48
+    var image = document.getElementById("myCanvas").toDataURL("image/png").replace("image/png", "image/octet-stream");
49
+    var data = new FormData();
50
+    data["file"] = image;
51
+    console.log(data);
52
+    $.ajax({
53
+        url: 'http://localhost:9000/upload/',
54
+        type: 'POST',
55
+        data: data,
56
+        cache: false,
57
+        dataType: 'json',
58
+        processData: false, 
59
+        contentType: false,  
60
+        success: function( data , textStatus , jqXHR )
61
+        {                
62
+            if( typeof data.error === 'undefined' ) {                    
63
+                submitForm( event, data ); 
64
+            } else {                    
65
+                alert( 'ERRORS: ' + data.error ); 
66
+            }
67
+        },
68
+        error: function(jqXHR, textStatus, errorThrown) { alert( 'error on upload' ); }
69
+        
70
+    });
71
+}
72
+
73
+function getDstImage(data) {
74
+    console.log("Entering into getDstImage")
75
+    var fname = "./img/"
76
+    switch(data["classification"]) {
77
+        case 1:
78
+            return fname+"1.jpg"
79
+        case 2:
80
+            return fname+"2.png"
81
+        case 3:
82
+            return fname+"3.png"
83
+        case 4:
84
+            return fname+"4.jpg"
85
+        case 5:
86
+            return fname+"5.png"
87
+        case 6:
88
+            return fname+"6.jpg"
89
+        case 7:
90
+            return fname+"7.png"
91
+        case 8:
92
+            return fname+"8.png"
93
+        case 9:
94
+            return fname+"9.png"
95
+        default:
96
+            return "error"
97
+    }
98
+}
99
+
100
+function uploadArea2() {
101
+    var canvas = document.getElementById("myCanvas")
102
+    canvas.toBlob(
103
+        function (blob) {
104
+            // Do something with the blob object,
105
+            // e.g. creating a multipart form for file uploads:
106
+            var formData = new FormData();
107
+            formData.append('file', blob, "predict.png");
108
+            $.ajax({
109
+                url: 'http://localhost:9000/upload/',
110
+                type: 'POST',
111
+                data: formData,
112
+                cache: false,
113
+                dataType: 'json',
114
+                processData: false, 
115
+                contentType: false,  
116
+                success: function( data , textStatus , jqXHR )
117
+                {                
118
+                    if( typeof data.error === 'undefined' ) {                    
119
+                        //submitForm( event, data ); 
120
+                    } else {                    
121
+                        alert( 'ERRORS: ' + data.error ); 
122
+                    }
123
+
124
+                    console.log("Inside success of uploadArea2")
125
+
126
+                    var canvas = document.getElementById("myCanvas2");
127
+                    var ctx = canvas.getContext("2d");
128
+                    var image = new Image();
129
+                    image.src = getDstImage(data);
130
+                    image.onload = function() {
131
+                        ctx.drawImage(image, 0, 0);
132
+                    };
133
+                },
134
+                error: function(jqXHR, textStatus, errorThrown) { alert( 'error on upload2' ); alert(textStatus);}
135
+                
136
+            });
137
+            /* ... */
138
+        },
139
+        'image/png'
140
+    );
141
+
142
+}
143
+
144
+function Draw(x, y, isDown) {
145
+    if (isDown) {
146
+        ctx.beginPath();
147
+        ctx.strokeStyle = $('#selColor').val();
148
+        // ctx.lineWidth = $('#selWidth').val();
149
+        ctx.lineWidth = 9;
150
+        ctx.lineJoin = "round";
151
+        ctx.moveTo(lastX, lastY);
152
+        ctx.lineTo(x, y);
153
+        ctx.closePath();
154
+        ctx.stroke();
155
+    }
156
+    lastX = x;
157
+    lastY = y;
158
+
159
+    //alert("Drawing done....");
160
+    //console.log("Drawing done.....");
161
+    //doUpload();
162
+} 
163
+
164
+function clearArea() {
165
+    // Use the identity matrix while clearing the canvas
166
+    ctx.setTransform(1, 0, 0, 1, 0, 0);
167
+    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
168
+    ctx2.setTransform(1, 0, 0, 1, 0, 0);
169
+    ctx2.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
170
+}

+ 2
- 0
examples/KnowThyNumber/FE/canvas-to-blob.min.js View File

@@ -0,0 +1,2 @@
1
+!function(t){"use strict";var e=t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype,o=t.Blob&&function(){try{return Boolean(new Blob)}catch(t){return!1}}(),n=o&&t.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(t){return!1}}(),r=t.BlobBuilder||t.WebKitBlobBuilder||t.MozBlobBuilder||t.MSBlobBuilder,a=/^data:((.*?)(;charset=.*?)?)(;base64)?,/,i=(o||r)&&t.atob&&t.ArrayBuffer&&t.Uint8Array&&function(t){var e,i,l,u,c,f,b,d,B;if(!(e=t.match(a)))throw new Error("invalid data URI");for(i=e[2]?e[1]:"text/plain"+(e[3]||";charset=US-ASCII"),l=!!e[4],u=t.slice(e[0].length),c=l?atob(u):decodeURIComponent(u),f=new ArrayBuffer(c.length),b=new Uint8Array(f),d=0;d<c.length;d+=1)b[d]=c.charCodeAt(d);return o?new Blob([n?b:f],{type:i}):((B=new r).append(f),B.getBlob(i))};t.HTMLCanvasElement&&!e.toBlob&&(e.mozGetAsFile?e.toBlob=function(t,o,n){var r=this;setTimeout(function(){t(n&&e.toDataURL&&i?i(r.toDataURL(o,n)):r.mozGetAsFile("blob",o))})}:e.toDataURL&&i&&(e.toBlob=function(t,e,o){var n=this;setTimeout(function(){t(i(n.toDataURL(e,o)))})})),"function"==typeof define&&define.amd?define(function(){return i}):"object"==typeof module&&module.exports?module.exports=i:t.dataURLtoBlob=i}(window);
2
+//# sourceMappingURL=canvas-to-blob.min.js.map

BIN
examples/KnowThyNumber/FE/img/1.png View File


BIN
examples/KnowThyNumber/FE/img/2.png View File


BIN
examples/KnowThyNumber/FE/img/3.png View File


BIN
examples/KnowThyNumber/FE/img/4.jpg View File


BIN
examples/KnowThyNumber/FE/img/5.png View File


BIN
examples/KnowThyNumber/FE/img/6.jpg View File


BIN
examples/KnowThyNumber/FE/img/7.png View File


BIN
examples/KnowThyNumber/FE/img/8.png View File


BIN
examples/KnowThyNumber/FE/img/9.png View File


BIN
examples/KnowThyNumber/FE/img/me_gopher.png View File


+ 64
- 0
examples/KnowThyNumber/FE/index.html View File

@@ -0,0 +1,64 @@
1
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
+
3
+<html>
4
+<head>
5
+        <meta charset="utf-8">
6
+        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
7
+        <!-- meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no" -->
8
+        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
9
+        <script type="text/javascript" src="map-touch-events.js"></script>
10
+        <script type="text/javascript" src="canvas-to-blob.min.js"></script>
11
+        <script type="text/javascript" src="JsCode.js"></script>
12
+        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
13
+        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
14
+        <style>
15
+            img{
16
+                max-width:100%
17
+            }
18
+        </style>
19
+</head>
20
+<body onload="InitThis();">
21
+    <div class="container">
22
+    <div class="jumbotron">
23
+    <center> <h1>Know Thy Numbers....</h1></center>
24
+    <p></p>
25
+    <center>
26
+    <table>
27
+    <tr>
28
+    <td><img src="img/me_gopher.png"><br /><br /> <center><button id="clear-area" onclick="javascript:clearArea();return false;">Clear Area</button>
29
+        <br /> <button id="upload-area" onclick="javascript:uploadArea2()">Predict</button></center></td>
30
+    <td>
31
+    <table>
32
+        <tr><th><center>Draw Here</center></th><th><center>Did you drew this...?</center></th></tr>
33
+        <tr>
34
+            <td>
35
+                <div id="input">
36
+                    <canvas id="myCanvas" width="150" height="350" style="border:2px solid black"></canvas>
37
+                </div>
38
+            </td>
39
+            <td>
40
+                <div id="prediction">
41
+                    <canvas id="myCanvas2" width="150" height="350" style="border:2px solid black"></canvas>
42
+                </div>
43
+            </td>
44
+        </tr>
45
+    </table>
46
+    </td></tr></table>
47
+    <br /><br />
48
+    <!-- button onclick="javascript:clearArea();return false;">Clear Area</button -->
49
+    <!-- button id="clear-area">Clear Area</button -->
50
+    <!-- button id="upload-area" onclick="javascript:doUpload();return false;">Predict</button -->
51
+    <!-- td -->
52
+    <br /><br />
53
+    Color : <select id="selColor" class="form-control">
54
+        <option value="black">black</option>
55
+        <option value="blue" selected="selected">blue</option>
56
+        <option value="red">red</option>
57
+        <option value="green">green</option>
58
+        <option value="yellow">yellow</option>
59
+        <option value="gray">gray</option>
60
+    </select>
61
+    </center>
62
+    </div></div>
63
+</body>
64
+</html>

+ 36
- 0
examples/KnowThyNumber/FE/map-touch-events.js View File

@@ -0,0 +1,36 @@
1
+function mapTouchEvents(event,simulatedType) {
2
+	
3
+	//Ignore any mapping if more than 1 fingers touching 
4
+	if(event.changedTouches.length>1){return;}
5
+	
6
+	var touch = event.changedTouches[0];
7
+	
8
+	//--https://developer.mozilla.org/en/DOM/document.createEvent--
9
+	eventToSimulate = document.createEvent('MouseEvent');
10
+	
11
+	//--https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent--
12
+	eventToSimulate.initMouseEvent(
13
+		simulatedType,		//type
14
+		true,				//bubbles
15
+		true,				//cancelable
16
+		window,				//view
17
+		1,					//detail
18
+		touch.screenX,		//screenX
19
+		touch.screenY,		//screenY
20
+		touch.clientX,		//clientX
21
+		touch.clientY,		//clientY
22
+		false,				//ctrlKey
23
+		false,				//altKey
24
+		false,				//shiftKey
25
+		false,				//metaKey
26
+		0,					//button
27
+		null				//relatedTarget
28
+	);
29
+
30
+	touch.target.dispatchEvent(eventToSimulate);
31
+	//This ignores the default scroll behavior
32
+	event.preventDefault();				
33
+	
34
+}
35
+
36
+

+ 21
- 0
examples/KnowThyNumber/LICENSE View File

@@ -0,0 +1,21 @@
1
+MIT License
2
+
3
+Copyright (c) 2018 Viswanath Kumar Skand Priya
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.

+ 2
- 0
examples/KnowThyNumber/README.md View File

@@ -0,0 +1,2 @@
1
+# KnowThyNumber
2
+A Test ( mobile ) WebApp to show the power of Openstack Gyan

Loading…
Cancel
Save