-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.R
98 lines (77 loc) · 2.57 KB
/
utils.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
# 微信数据截取函数
extractWeixin = function(msgXML, pattern,CDATA = T){
if(CDATA)
regPattern = paste0("(?<=", pattern, "><\\!\\[CDATA\\[)[\\s\\S]+(?=\\]\\]></",
pattern, ")")
else
regPattern = paste0("(?<=", pattern, ">).+(?=</",
pattern, ")")
regmatches(msgXML,
gregexpr(regPattern,
msgXML,
perl = TRUE))[[1]]
}
if(!require(mxnet)){
install.packages("drat", repos="https://cran.rstudio.com")
drat:::addRepo("dmlc")
install.packages("mxnet")
}
library(mxnet)
library(imager)
# 载入模型
model = mx.model.load("Inception/Inception_BN", iteration=39)
# 载入mean image
mean.img = as.array(mx.nd.load("Inception/mean_224.nd")[["mean_img"]])
im <- load.image(system.file("extdata/parrots.png", package = "imager"))
plot(im)
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)
cropped <- crop.borders(im, xx, yy)
# resize to 224 x 224, needed by input of the model.
resized <- resize(cropped, 224, 224)
# convert to array (x, y, channel)
arr <- as.array(resized) * 255
dim(arr) <- c(224, 224, 3)
# subtract the mean
normed <- arr - mean.img
# Reshape to format needed by mxnet (width, height, channel, num)
dim(normed) <- c(224, 224, 3, 1)
return(normed)
}
normed <- preproc.image(im, mean.img)
prob <- predict(model, X=normed)
max.idx <- max.col(t(prob))
synsets <- readLines("Inception/synset.txt")
print(paste0("Predicted Top-class: ", synsets[[max.idx]]))
showPic = function(input){
cat <- load.image(input)
# plot(cat)
normed <- preproc.image(cat, mean.img)
prob <- predict(model, X=normed)
max.idx <- max.col(t(prob))
print(paste0("Predicted Top-class: ", synsets[[max.idx]]))
output = strsplit(synsets[[max.idx]]," ")[[1]]
output[1] = ''
return(paste(output,collapse=" "))
}
returnMsg = function(ori,user, time, msgType, content, messageId,PicUrl){
if(length(PicUrl)==0){
cat(234)
return('success')
}
cat(123)
filename = paste0("data/",format(Sys.time(),"%Y%m%d%M"))
download.file(PicUrl,destfile = filename)
output = sprintf("<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[介尼玛似一个%s]]></Content>
</xml>",user,ori,as.numeric(Sys.time()),showPic(filename))
return(output)
}