-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBilderkennung.py
executable file
·179 lines (151 loc) · 5.41 KB
/
Bilderkennung.py
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python3
#AI_Model_Creator; an easy to use AI cumputer vision model creator.
#Copyright (C) 2020 Jonas Mayer
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <https://www.gnu.org/licenses/>.
#You can contact me by mail: [email protected]
import sys
syspath0=sys.path[0]
exec(open(sys.path[0]+"/../../../../VirtualPython3/bin/activate_this.py").read(), {'__file__': sys.path[0]+"/../../../../VirtualPython3/bin/activate_this.py"})
#exec(open(sys.path[0]+"/VirtualPython3/bin/activate_this.py").read(), {'__file__': sys.path[0]+"/VirtualPython3/bin/activate_this.py"})
sys.path.append(sys.path[0])
sys.path[0] = syspath0
sys.path.insert(0,sys.path[0]+"/../../../../VirtualPython3/lib/python3.6/dist-packages")
import rospy,roslib
import cv2
from cv2 import *
from torchvision import transforms
import os
from PIL import Image
import numpy as np
import torch
from sensor_msgs.msg import Image as imageMsg
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import sys
import timeit
from cv_bridge import CvBridge, CvBridgeError
import topic_names
import std_msgs
from torch import nn,optim,utils,exp,stack,autograd,save,load
from torchvision import transforms,models,datasets
import os
import time
from PIL import Image
rospy.init_node("bilderkennung_ki")
normalize = transforms.Normalize(
mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225]
)
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(256),
transforms.ToTensor(),
normalize
])
if rospy.has_param("/model_name"):
model_name = rospy.get_param("/model_name")
path = sys.path[0]+"/../../../../Models/"+model_name+"/"
#path = sys.path[0]+"/Models/"
try:
modelUClasses = torch.load(path+model_name+".pt")
print(modelUClasses)
except FileNotFoundError:
model = models.vgg16(pretrained=True)
print("model wurde mit namen",'"'+model_name+'"',"wurde noch nicht erstellt.\n Bitte schaue hier nach deinem Model",path+model_name+".pt")
model = modelUClasses["model"]
classes = modelUClasses["classes"]
model.eval()
else :
print("Rosparam /model_name not set")
outWrite = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (640,480))
i = 0
def image_callback(image):
global i
global outWrite
i +=1
bridge = CvBridge()
cv_image = bridge.imgmsg_to_cv2(image, desired_encoding="passthrough")
imageData = transform(Image.fromarray(cv_image)) #to bring it in form 1*3*255*255
inpt=torch.Tensor(imageData.unsqueeze(0))
inpt = Variable(inpt)
out = model(inpt)
out = torch.exp(out)
namenTest=[]
prop = 0.5
for i in range(len(out)):
a =0
for proz in out[i]:
if float(proz)>0.8:
namenTest.append(classes[a])
prop = proz
a=a+1
if len(namenTest) == 0:
namenTest.append("None")
classifiedName_pub.publish(namenTest[0])
print("Das erkannte Objekt ist: ["+str(namenTest[0])+"] mit einer Wahrscheinlichkeit von "+str(int(prop*100.0))+"% \n",out[i],classes)
if i > 400:
outWrite.release()
else:
outWrite.write(cv_image)
classifiedName_pub = rospy.Publisher(topic_names.classified_name_topic(), std_msgs.msg.String, queue_size=10)
rospy.Subscriber(topic_names.raw_image_topic(),imageMsg,image_callback)
while not rospy.core.is_shutdown():
rospy.rostime.wallsleep(0.5)
""" try:
model.load_state_dict(load("/home/jonas/git/sfz_cvb/Models/testGolf2.pt"))
except:
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.classifier.parameters(),lr=0.0001)
def trainClassifier():
epochs = 30
steps = 0
for e in range(epochs):
model.train()
for image,label in iter(trainImages):
steps +=1
optimizer.zero_grad()
output = model.forward(image)
print(output.size())
loss = criterion(output,label)
loss.backward()
optimizer.step()
print(str(loss.data)+" ev "+str(e))
trainClassifier()
save(model.state_dict(),"testsave.pt")
for images,labels in iter(testImages):
output = model.forward(images)
print(output.size())
output = exp(output)
print("Der Output ist: "+str(output)+" und sollte das sein: "+str(labels))
i=2
while i <= 13:
array = []
Img = Image.open("/home/jonas/Schreibtisch/PicsKiGolfHell/"+"Test"+str(i)+".jpeg")
array.append(transformTest(Img))
print("start")
out=model(autograd.Variable(stack(array)))
print(output.size())
out = exp(out)
print("end")
a =0
name="none"
print(out[0])
for proz in out[0]:
if float(proz)>0.8:
name=classes[a]
a=a+1
Img.show()
print(name)
time.sleep(5)
i=i+1 """