forked from nanxstats/imgsvd
-
Notifications
You must be signed in to change notification settings - Fork 30
/
server.R
111 lines (102 loc) · 2.68 KB
/
server.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
require(mxnet)
require(imager)
require(shiny)
require(jpeg)
require(png)
if (!file.exists("synset.txt")) {
download.file("http://data.dmlc.ml/mxnet/models/imagenet/inception-bn.tar.gz", destfile = "inception-bn.tar.gz")
untar("inception-bn.tar.gz")
}
model <<- mx.model.load("./Inception-BN", iteration = 126)
synsets <<- readLines("synset.txt")
preproc.image <- function(im, mean.image) {
# crop the image
shape <- dim(im)
short.edge <- min(shape[1:2])
xx <- floor((shape[1] - short.edge) / 2)
yy <- floor((shape[2] - short.edge) / 2)
croped <- crop.borders(im, xx, yy)
# resize to 224 x 224, needed by input of the model.
resized <- resize(croped, 224, 224)
# convert to array (x, y, channel)
arr <- as.array(resized) * 255
dim(arr) <- c(224, 224, 3)
# substract the mean
normed <- arr - 117
# Reshape to format needed by mxnet (width, height, channel, num)
dim(normed) <- c(224, 224, 3, 1)
return(normed)
}
shinyServer(function(input, output) {
ntext <- eventReactive(input$goButton, {
print(input$url)
if (input$url == "http://") {
NULL
} else {
tmp_file <- tempfile()
download.file(input$url, destfile = tmp_file)
tmp_file
}
})
output$originImage = renderImage({
list(src = if (input$tabs == "Upload Image") {
if (is.null(input$file1)) {
if (input$goButton == 0 || is.null(ntext())) {
'cthd.jpg'
} else {
ntext()
}
} else {
input$file1$datapath
}
} else {
if (input$goButton == 0 || is.null(ntext())) {
if (is.null(input$file1)) {
'cthd.jpg'
} else {
input$file1$datapath
}
} else {
ntext()
}
},
title = "Original Image")
}, deleteFile = FALSE)
output$res <- renderText({
src = if (input$tabs == "Upload Image") {
if (is.null(input$file1)) {
if (input$goButton == 0 || is.null(ntext())) {
'cthd.jpg'
} else {
ntext()
}
} else {
input$file1$datapath
}
} else {
if (input$goButton == 0 || is.null(ntext())) {
if (is.null(input$file1)) {
'cthd.jpg'
} else {
input$file1$datapath
}
} else {
ntext()
}
}
im <- load.image(src)
normed <- preproc.image(im, mean.img)
prob <- predict(model, X = normed)
max.idx <- order(prob[,1], decreasing = TRUE)[1:5]
result <- synsets[max.idx]
res_str <- ""
for (i in 1:5) {
tmp <- strsplit(result[i], " ")[[1]]
for (j in 2:length(tmp)) {
res_str <- paste0(res_str, tmp[j])
}
res_str <- paste0(res_str, "\n")
}
res_str
})
})