-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageProcessing.py
More file actions
313 lines (192 loc) · 10.9 KB
/
Copy pathImageProcessing.py
File metadata and controls
313 lines (192 loc) · 10.9 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import cv2
import math
import easyocr
import numpy as np
from mss import mss
MainMss = mss()
reader = easyocr.Reader(['en'], gpu = False)
def GetDistance(MobCenterX, MobCenterY, PatryMember):
distanceEvcl = abs(math.hypot(MobCenterX - PatryMember.WindowCentrX, MobCenterY - PatryMember.WindowCentrY))
distanceJustY = abs(PatryMember.WindowCentrY - MobCenterY)
distanceJustX = abs(PatryMember.WindowCentrX - MobCenterX)
return (distanceEvcl + distanceJustY + distanceJustX) / 2
def GetBoundingBox(top, left, width, height):
return {'top': top, 'left': left, 'width': width, 'height': height}
def GetScreen(BoundingBox, PatryMember, ForRadar):
image = MainMss.grab(GetBoundingBox(0, 0, 1, 1))
image = MainMss.grab(BoundingBox)
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGRA2BGR)
if ForRadar:
image[0:PatryMember.WindowHeight, 0:(PatryMember.WindowCentrX-300)] = (0, 0, 0) # Левая часть экрана, скрывающая персонажей
image[0:PatryMember.WindowHeight, (PatryMember.WindowCentrX+300):(PatryMember.WindowWidth)] = (0, 0, 0) # Правая часть экрана, скрывающая карту
image[0:(PatryMember.WindowCentrY-300), 0:(PatryMember.WindowWidth)] = (0, 0, 0) # Верхняя часть экрана, скрывающая бафы, именя целей
else:
image[0:200, 0:180] = (0, 0, 0) # Левая часть экрана, скрывающая персонажей
image[0:50, 0:BoundingBox['width']] = (0, 0, 0) # Верхняя часть экрана, скрывающая бафы, именя целей
return image
def GetContours(image):
# Значения получены экперементальным путем. Модуль CheckImageConvert используется для
# определения значений на конретных условиях использования
# lower = np.array([0, 0, 190])
# upper = np.array([40, 40, 255])
lower = np.array([150, 0, 255])
upper = np.array([180, 255, 255])
# Convert to HSV format and color threshold
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
# to manipulate the orientation of dilution , large x means horizonatally dilating more, large y means vertically dilating more
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
# dilate , more the iteration more the dilation
# Используется для более четкого определение границ с имена целей
dilated = cv2.dilate(mask, kernel, iterations=9)
# findContours returns 3 variables for getting contours
contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Испольузется для сохранения в файлы имен целей
DilatedToCreateFiles = cv2.dilate(mask, kernel, iterations=1)
return contours, mask, DilatedToCreateFiles
def GetCurrentTargetsFromContours(Targets, Contours, DilatedImage, PatryMember):
CurrentTargets = {}
for contour in Contours:
[x, y, w, h] = cv2.boundingRect(contour)
if (w < 35 and h < 35) or (w > 200):
continue
ImageFromContour = DilatedImage[y:y + h, x:x + w]
TargetName, TargetType = GetTargetNameFromTargetsListImage(Targets, ImageFromContour)
if TargetName is None:
continue
MobCenterX = int(x + (w/2)) - 5
MobCenterY = int(y + h) #int(y + (h/2)) + 20#50 Отступ от нижней гранцы рамки (имени) до "головы" монстра
distance = GetDistance(MobCenterX, MobCenterY, PatryMember)
CurrentTargets[distance] = {'TargetName': TargetName, 'TargetType': TargetType,
'CenterX': MobCenterX, 'CenterY': MobCenterY,
'rectangleX': x, 'rectangleY': y,
'rectangleW': x + w, 'rectangleH': y + h}
return CurrentTargets
def MatchTemplate(TargetNameImage, ImageFromContour):
wth, hth = ImageFromContour.shape
wtp, htp = TargetNameImage.shape
if not (wth >= wtp and hth >= htp):
return False
res = cv2.matchTemplate(TargetNameImage, ImageFromContour, cv2.TM_CCORR_NORMED)
if not res.any():
return False
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val > 0.8:
return True
return False
def GetTargetNameFromTargetsListImage(Targets, ImageFromContour):
#TargetType = 1 - TargetFromList
#TargetType = 2 - TargetAgressiveList
#TargetType = 3 - TargetStoptList
for TargetFromList in Targets.TargetList:
if MatchTemplate(TargetFromList[1], ImageFromContour):
return TargetFromList[0], 1
for TargetFromList in Targets.TargetAgressiveList:
if MatchTemplate(TargetFromList[1], ImageFromContour):
return TargetFromList[0], 2
for TargetFromList in Targets.TargetStoptList:
if MatchTemplate(TargetFromList[1], ImageFromContour):
return TargetFromList[0], 3
return None, None
def GetTargetNameFromImage(image, reader, TargetCacheNames):
# Распознование текта по картинке не совсем точное и главное быстрое, например,
# для имени Glow могут возвращаться следующие комбинации: 'Glot', 'Glo#', 'Glow', 'Gloit IWied', 'Gio#'
# что затрудянет опознование, но использование кеша с именама и данными изображений скорость работы
# заметно увеличивается
TargetName = ""
TargetKey = image.tobytes()
img = cv2.resize(image, (0,0), fx=3, fy=3)
kernel = np.ones((5,5), np.uint8)
dilation = cv2.dilate(img, kernel, iterations = 1)
if not TargetKey in TargetCacheNames:
bounds = reader.readtext(dilation)
if len(bounds) > 0:
TargetName = bounds[0][1]
TargetCacheNames[TargetKey] = TargetName
else:
TargetName = TargetCacheNames[TargetKey]
return TargetName
def GetNearestTarget(image, Targets, CurrentTargets, PatryMember, DisplayGraphicElements):
nearestX = 0
nearestY = 0
TargetType = 0
distanceMinTargetList = 10000
distanceMinTargetStoptList = 10000
distanceMinTargetAgressiveList = 10000
for TargetID in CurrentTargets:
CurrentTarget = CurrentTargets[TargetID]
TargetName = CurrentTarget["TargetName"]
TargetColor = None
TargetDistance = TargetID
if CurrentTarget["TargetType"] == 1:
TargetColor = Targets.TargetListColor
distanceMinTargetList = min(distanceMinTargetList, TargetDistance)
elif CurrentTarget["TargetType"] == 2:
TargetColor = Targets.TargetListColor
distanceMinTargetAgressiveList = min(distanceMinTargetAgressiveList, TargetDistance)
elif CurrentTarget["TargetType"] == 3:
TargetColor = Targets.TargetStopListColor
distanceMinTargetStoptList = min(distanceMinTargetStoptList, TargetDistance)
if DisplayGraphicElements:
if not TargetColor is None:
cv2.rectangle(image, (CurrentTarget["rectangleX"], CurrentTarget["rectangleY"]), (CurrentTarget["rectangleW"], CurrentTarget["rectangleH"]),
TargetColor, 1)
cv2.line(image, (PatryMember.WindowCentrX, PatryMember.WindowCentrY),
(CurrentTarget["CenterX"], CurrentTarget["CenterY"]), TargetColor, 1)
cv2.putText(image, str(round(TargetDistance, 2)),
(CurrentTarget["rectangleX"], CurrentTarget["rectangleY"] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.3, TargetColor)
else:
cv2.rectangle(image, (CurrentTarget["rectangleX"], CurrentTarget["rectangleY"]), (CurrentTarget["rectangleW"], CurrentTarget["rectangleH"]),
(0, 255, 255), 2)
cv2.putText(image, TargetName,
(CurrentTarget["rectangleX"], CurrentTarget["rectangleY"] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 255, 255))
distanceMin = min(distanceMinTargetList, distanceMinTargetAgressiveList)
if distanceMinTargetAgressiveList < 250:
distanceMin = distanceMinTargetAgressiveList
if distanceMin < 10000 and distanceMinTargetStoptList > 250:
CurrentTarget = CurrentTargets[distanceMin]
nearestX = CurrentTarget["CenterX"]
nearestY = CurrentTarget["CenterY"]
TargetType = CurrentTarget["TargetType"]
if DisplayGraphicElements:
cv2.rectangle(image, (CurrentTarget["rectangleX"], CurrentTarget["rectangleY"]),
(CurrentTarget["rectangleW"], CurrentTarget["rectangleH"]),
Targets.NextTargetColor, 2)
cv2.line(image, (PatryMember.WindowCentrX, PatryMember.WindowCentrY),
(CurrentTarget["CenterX"], CurrentTarget["CenterY"]), Targets.NextTargetColor, 2)
return nearestX, nearestY, TargetType
def CheckTargetMarker(roi, template):
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
ret, th1 = cv2.threshold(roi, 224, 255, cv2.THRESH_TOZERO_INV)
#cv2.imwrite('./Screens/th1.png', th1)
ret, th2 = cv2.threshold(th1, 135, 255, cv2.THRESH_BINARY)
#cv2.imwrite('./Screens/th2.png', th2)
ret, tp1 = cv2.threshold(template, 224, 255, cv2.THRESH_TOZERO_INV)
#cv2.imwrite('./Screens/tp1.png', tp1)
ret, tp2 = cv2.threshold(tp1, 135, 255, cv2.THRESH_BINARY)
#cv2.imwrite('./Screens/tp2.png', tp2)
if not hasattr(th2, 'shape'):
return False
wth, hth = th2.shape
wtp, htp = tp2.shape
if wth > wtp and hth > htp:
res = cv2.matchTemplate(th2, tp2, cv2.TM_CCORR_NORMED)
if res.any():
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val > 0.7:
return True
else:
return False
return False
def TargetIsPet(PetNameTemplateImage):
BoundingBox = GetBoundingBox(34, 390, 170, 20)
roi = MainMss.grab(BoundingBox)
roi = cv2.cvtColor(np.array(roi), cv2.COLOR_BGR2GRAY)
ret, th1 = cv2.threshold(roi, 224, 255, cv2.THRESH_TOZERO_INV)
ret, th2 = cv2.threshold(th1, 135, 255, cv2.THRESH_BINARY)
return MatchTemplate(th2, PetNameTemplateImage)
def PersonIsDied(DiedTargetTemplateImage, Image):
roi = cv2.cvtColor(Image, cv2.COLOR_BGR2GRAY)
ret, th1 = cv2.threshold(roi, 224, 255, cv2.THRESH_TOZERO_INV)
ret, th2 = cv2.threshold(th1, 135, 255, cv2.THRESH_BINARY)
return MatchTemplate(DiedTargetTemplateImage, th2)