JapanKanji

Форк
0
/
xyCreate.py 
624 строки · 22.3 Кб
1
import datetime
2
import sys, os
3

4
import cv2 as cv2
5
import numpy as np
6

7
import pandas as pd
8
import matplotlib.pyplot as plt
9

10
from formSubs import s, softmax
11

12
###############################################################################################
13

14

15
def xTrainCreate (nameFiles, shape_net, dirFiles='.', 
16
                  bwOK=True, norm=True, stats=False) :
17
    
18
    dd = [1,] if bwOK else [3,]
19
    bw = 0    if bwOK else -1
20
    
21
    zxtrain    = np.zeros([len(nameFiles),]+list(shape_net), dtype=np.float32)
22
    
23
    scale_all    = []
24
    shape_in_all = []
25

26
    for ii,image_id in enumerate(nameFiles) :
27
        img      = cv2.imread(os.path.join(dirFiles,image_id+'.jpg'),bw)
28
        shape_in = img.shape[:2]
29
        scale    =  min(np.array(shape_net[:2])/np.array(shape_in[:2]));
30

31
        newX,newY = shape_in[1]*scale, shape_in[0]*scale
32
        newimg = cv2.resize(img,(int(newX),int(newY)))
33

34
        
35
        if stats :
36
            if ii==0 : means, stds = [], []
37
            means.append(newimg.mean())
38
            stds.append(newimg.std())
39

40
        newimg = newimg.astype(np.float64)
41
        newimg = newimg-newimg.mean()
42
        #newimg = newimg/127.0
43
        newimg = newimg/max(abs(newimg.min()),abs(newimg.max()))
44

45
        ##newimg = newimg/newimg.std()
46

47
        ###newimg = np.clip(newimg,-1.0,1.0) ####### shift mean on +0.15
48
            
49
        if bwOK : newimg = newimg.reshape(newimg.shape+(1,))
50
        zxtrain[ii,:int(newY),:int(newX)] = newimg
51
        scale_all.append(scale)
52
        shape_in_all.append(shape_in)
53
        
54
    scale_all    = np.array(scale_all)
55
    shape_in_all = np.array(shape_in_all)
56
    
57
    if stats : return(zxtrain,scale_all,shape_in_all,np.array(means),np.array(stds))
58

59
    return(zxtrain,scale_all,shape_in_all)
60

61

62
###############################################################################################
63

64
def xCreate2 (nameFile, shape_net, bwOK=True, coef=0.3) :
65
    
66
    dd = [1,] if bwOK else [3,]
67
    bw = 0    if bwOK else -1
68
    
69
    zx        = np.zeros(shape_net, dtype=np.float32)
70
    
71
    img       = cv2.imread(nameFile,bw)
72
    shape_in  = img.shape[:2]
73
    
74
    img       = cv2.resize(img,(int(coef*shape_in[1]),int(coef*shape_in[0])))
75
    #shape_in  = img.shape[:2]
76
        
77
    newimg    = img.astype(np.float64)
78
    newimg    = newimg-newimg.mean()
79
    newimg    = newimg/(np.abs(newimg)).max()
80
    
81
    if bwOK : newimg = newimg.reshape(newimg.shape+(1,))
82

83
    deltas, x = [], []
84
    
85
    for rr in range(0,shape_in[0],shape_net[0]) :
86
        for cc in range(0,shape_in[1],shape_net[1]) :
87
            xx   = zx.copy()
88
            ximg = newimg[rr:rr+shape_net[0],cc:cc+shape_net[1]] 
89
            xx[0:ximg.shape[0],0:ximg.shape[1]] = ximg
90
            if (xx==0.0).all() : continue
91
            #xx   = xx.reshape((1,)+xx.shape)
92
            x.append(xx)
93
            deltas.append([rr,cc])
94
            
95
    x = np.stack(x,axis=0)
96
            
97
    return(x,deltas,shape_in,img.mean(),img.std())
98

99
###############################################################################################
100

101
def CLAHEF (image_path, two=False, **kwarg) :
102
    rgb = cv2.imread(image_path)
103
    if two : return(rgb,CLAHEA(rgb,**kwarg))
104
    return(CLAHEA(rgb,**kwarg))
105

106
def CLAHEA (rgb, gridsize=(94,77)) :
107
    lab = cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)
108
    lab_planes = cv2.split(lab)
109
    clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=gridsize) #(gridsize,gridsize))
110
    lab_planes[0] = clahe.apply(lab_planes[0])
111
    lab = cv2.merge(lab_planes)
112
    rgb1= cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)
113
    return(rgb1)
114

115
def CLAHEAGray (gray, gridsize=(94,77)) :
116
    clahe = cv2.createCLAHE(clipLimit=1.0,tileGridSize=gridsize) #(gridsize,gridsize))
117
    gray1 = clahe.apply(gray)
118
    return(gray1)
119

120
def xCreate2F (nameFile, shape_net, bwOK=True, scale=0.3, 
121
               contrast=True, clahe=False, count=None,
122
               **kwarg) :
123
    
124
    dd = (1,) if bwOK else (3,)
125
    bw = 0    if bwOK else -1
126
    
127
    zx        = np.zeros(shape_net, dtype=np.float32)
128
    
129
    img       = cv2.imread(nameFile,bw)
130
    shape_in  = img.shape[:2]
131
    
132
    if clahe and img.ndim==2 : img = CLAHEAGray(img)
133
    
134
    if type(scale)==type(2.6) or type(scale)==type(2) : # scale_ is float 
135
        scale_  = scale
136
        newsize=(int(scale_*shape_in[1]),int(scale_*shape_in[0]))
137
        newimg    = cv2.resize(img,newsize)
138
    else :                                              # scale_ is list or tuple (rows,columns) - new size
139
        scale_    = min(1.0,min(scale[0]/shape_in[0],scale[1]/shape_in[1]))
140
        newsize   = (int(shape_in[1]*scale_),int(shape_in[0]*scale_))
141
        #print('????',scale,scale_,shape_in,newsize)
142
        newimg    = cv2.resize(img,newsize)
143
        
144
    if img.ndim==2 :
145
        if 1 :
146
            newimg    = newimg.astype(float)
147
            newimg    = newimg-newimg.mean()
148
            if contrast : newimg    = newimg/(np.abs(newimg)).max()
149
        if 1 :
150
            newimg    = np.clip((newimg*127+127),0,255).astype(np.uint8)
151
    
152
    if bwOK : newimg = newimg.reshape(newimg.shape+dd)
153

154
    deltas, x = [], []
155
    
156
    zx        = np.zeros(shape_net, dtype=newimg.dtype)
157
    
158
    #print(newimg.shape,shape_net)
159
    
160
    for rr in range(0,newimg.shape[0],shape_net[0]) :
161
        for cc in range(0,newimg.shape[1],shape_net[1]) :
162
            xx   = zx.copy()
163
            ximg = newimg[rr:rr+shape_net[0],cc:cc+shape_net[1]] 
164
            
165
            xx[0:ximg.shape[0],0:ximg.shape[1]] = ximg.copy()
166
            
167
            if rr>0 or cc>0 :
168
                if count is not None and count==0 and ximg.size <= 0.75*zx.size : continue
169
                if count is not None and ximg.size <= 0.5*zx.size : continue
170
            
171
                if (xx==255).all() : continue
172
                if (xx==127).all() : continue
173
                if (xx==0).all()   : continue
174
            
175
            #xx   = xx.reshape((1,)+xx.shape)
176
            x.append(xx.copy())
177
            deltas.append([rr,cc])
178
            
179
            #plt.imshow(xx.squeeze());
180
            #plt.show()
181
     
182
    x = np.stack(x,axis=0)
183
    #x = np.stack(x)
184
            
185
    return(x,deltas,scale_,shape_in,img.mean(),img.std())
186

187
def xCreate2FF(dirData, nFiles_, shape_net, ext='.jpg', counts=None, **kwarg) :
188
    nFiles = nFiles_
189
    if ext is not None : nFiles = [nFile+ext for nFile in nFiles]
190
        
191
    aCount, count = 0, None
192
    for ii,nFile in enumerate(nFiles) :
193
        if counts is not None : count = counts[ii]
194
        xdata, deltas, scale, shape_in, xmean, xstd = xCreate2F(os.path.join(dirData,nFile), 
195
                                                                shape_net, count=count, **kwarg)
196
        aCount = aCount + len(xdata)
197
        
198
    for ii,nFile in enumerate(nFiles) :
199
        if counts is not None : count = counts[ii]
200
        xdata, xdelta, scale, shape_in, xmean, xstd = xCreate2F(os.path.join(dirData,nFile), 
201
                                                                shape_net, count=count, **kwarg)
202
        if ii==0 :
203
            xdatas  = np.zeros((aCount,)+xdata[0].shape, dtype=xdata.dtype)
204
            xdeltas = []
205
            xscale  = np.zeros((len(nFiles),), dtype=float)
206
            xshape  = np.zeros((len(nFiles),len(shape_in)), dtype=int)
207
            iiCount = 0
208
        xdeltas.append(xdelta)
209
        xdatas[iiCount:iiCount+len(xdata)], xscale[ii], xshape[ii]  = xdata.copy(), scale, shape_in
210
        iiCount = iiCount+len(xdata)
211
        
212
    return xdatas,xdeltas,xscale,xshape
213

214
###############################################################################################
215

216
def yTrainCreate (numbers, trainY, classes, shape_net, shape_out, 
217
                  
218
                  anchorsl, scale_all, shape_in_all,
219
                  printOK=False) :
220

221
    n_anchors = len(anchorsl)
222
    array_size= len(numbers)
223

224
    ytrain    = np.zeros([array_size,]+list(shape_out), dtype=np.float32)
225

226
    train10   = np.zeros((5+len(classes)), dtype=np.float32)
227
    
228
    grid_net  = shape_net[0:2]/shape_out[0:2]
229

230
    cc1, cc2, cc3 =  0, 0, 0
231

232
    for iinn, ii in enumerate(numbers) :
233
        
234
        ll       =  trainY.iloc[[ii]].fillna('').labels.values[0];
235

236
        scale    =  scale_all[ii]               ### bug 2019-08-13  iinn --> ii
237
        shape_in =  shape_in_all[ii]            ### bug 2019-08-13  iinn --> ii
238
        anmax =  anchorsl
239

240
        ii1, ii2   =  0, 0
241

242
        lx5sort    =  np.array(ll.split()).reshape((-1,5))
243
        temp       =  lx5sort[:,3].astype(np.float32)*lx5sort[:,4].astype(np.float32)
244

245
        for lx5 in lx5sort[temp.argsort()] :
246

247
            # x,y,w,h - x columns, y rows
248
            lx4    = lx5[1:].astype(np.float32)
249

250
            if (((lx4[0]+lx4[2]/2)>=shape_in[1]) or ((lx4[1]+lx4[3]/2)>=shape_in[0])) :
251
                if (cc3<20) and printOK : 
252
                    print(trainY.image_id[ii], 'bad:', iinn, ii, np.round(lx4), 'shape_in:',shape_in)
253
                cc3 = cc3+1
254
                continue
255
                
256
            cclass = -1
257

258
            if len(classes)>0 :
259
                try    : cclass = classes.tolist().index(lx5[0])
260
                except : cclass = -1
261

262
            cc1 = cc1 + 1
263
            ii1 = ii1 + 1
264

265
            lx4    = lx5[1:].astype(np.float32)
266

267
            lx2max     =  lx5[3:].astype(np.float32)*scale
268
            temp       =  np.array([np.minimum(lx2max,anmax[jj]) for jj in range(len(anmax))])
269
            temp       =  temp[:,0]*temp[:,1]
270
            iou        =  temp/(np.add(anmax[:,0]*anmax[:,1],lx2max[0]*lx2max[1])-temp)
271

272
            ian        =  np.argmax(iou)
273

274
            tc         =  lx4[:2]+lx4[2:]/2
275
            tc         =  np.floor(tc*scale/(grid_net[1],grid_net[0])).astype(np.int32)
276

277
            lx4[:2]    = (lx4[:2]+lx4[2:]/2) # center point
278

279
            lx4[0:2]   = lx4[0:2]*scale/(shape_net[1],shape_net[0])
280
            lx4[2:4]   = lx4[2:4]*scale/(shape_net[1],shape_net[0])
281

282
            train1            = train10.copy().astype(np.float32)
283
            train1 [:]        = 0.0
284
            train1 [0]        = 1.0 if cclass>=0 or len(classes)==0 else 0.0 ###########!!!!!!!!!!!!!!!!!! 2019-08-08
285
            train1 [1:5]      = lx4
286
            if (len(classes)>0 and cclass>=0) : 
287
                train1 [5+cclass] = 1.0
288
                #print(iinn,tc[1],tc[0],ian)
289

290
            ianNew = ian
291
            try :
292
                while ytrain[ii,tc[1],tc[0],ianNew,0]==1.0 :
293
                    ianNew = (ianNew+1) % n_anchors
294
                    if ian==ianNew : break
295

296
                if ytrain[ii,tc[1],tc[0],ianNew,0]==1.0 :
297
                    cc2 = cc2 + 1
298
                    ii2 = ii2 + 1
299

300
            except :
301
                if  printOK :
302
                    print('except: ', ii, tc[1], tc[0], ianNew)
303
                    print('lx5 ',lx5)
304
                    print('lx4 ',lx4)
305
                    print('in:',shape_in)
306
                    print(lx4[0]*shape_net[1],lx4[1]*shape_net[0])
307
                    print(np.array(shape_net)/np.array(shape_in[:2]))
308

309
            ytrain[iinn,tc[1],tc[0],ianNew,:] = train1
310
            
311
    return (ytrain, (cc1,cc2,cc3))
312

313
###############################################################################################
314

315
def yTrainCreate2 (numbers, trainY, classes, shape_net, shape_out, 
316
                  
317
                  anchorsl, scale_all, shape_in_all,
318
                  printOK=False) :
319

320
    n_anchors = len(anchorsl)
321
    array_size= len(numbers)
322

323
    ytrain    = np.zeros([array_size,]+list(shape_out), dtype=np.float32)
324

325
    train10   = np.zeros((5+len(classes)), dtype=np.float32)
326
    
327
    grid_net  = shape_net[0:2]/shape_out[0:2]
328

329
    cc1, cc2, cc3 =  0, 0, 0
330

331
    for iinn, ii in enumerate(numbers) :
332
        
333
        ll       =  trainY[ii];
334

335
        scale    =  scale_all[ii]               ### bug 2019-08-13  iinn --> ii
336
        shape_in =  shape_in_all[ii]            ### bug 2019-08-13  iinn --> ii
337
        anmax =  anchorsl
338

339
        ii1, ii2   =  0, 0
340

341
        lx5sort    =  np.array(ll.split()).reshape((-1,5))
342
        temp       =  lx5sort[:,3].astype(np.float32)*lx5sort[:,4].astype(np.float32)
343

344
        for lx5 in lx5sort[temp.argsort()] :
345

346
            # x,y,w,h - x columns, y rows
347
            lx4    = lx5[1:].astype(np.float32)
348

349
            if (((lx4[0]+lx4[2]/2)>=shape_in[1]) or ((lx4[1]+lx4[3]/2)>=shape_in[0])) :
350
                if (cc3<20) and printOK : 
351
                    print(trainY.image_id[ii], 'bad:', iinn, ii, np.round(lx4), 'shape_in:',shape_in)
352
                cc3 = cc3+1
353
                continue
354
                
355
            cclass = -1
356

357
            if len(classes)>0 :
358
                try    : cclass = classes.tolist().index(lx5[0])
359
                except : cclass = -1
360

361
            cc1 = cc1 + 1
362
            ii1 = ii1 + 1
363

364
            lx4    = lx5[1:].astype(np.float32)
365

366
            lx2max     =  lx5[3:].astype(np.float32)*scale
367
            temp       =  np.array([np.minimum(lx2max,anmax[jj]) for jj in range(len(anmax))])
368
            temp       =  temp[:,0]*temp[:,1]
369
            iou        =  temp/(np.add(anmax[:,0]*anmax[:,1],lx2max[0]*lx2max[1])-temp)
370

371
            ian        =  np.argmax(iou)
372

373
            tc         =  lx4[:2]+lx4[2:]/2
374
            tc         =  np.floor(tc*scale/(grid_net[1],grid_net[0])).astype(np.int32)
375

376
            lx4[:2]    = (lx4[:2]+lx4[2:]/2) # center point
377

378
            lx4[0:2]   = lx4[0:2]*scale/(shape_net[1],shape_net[0])
379
            lx4[2:4]   = lx4[2:4]*scale/(shape_net[1],shape_net[0])
380

381
            train1            = train10.copy().astype(np.float32)
382
            train1 [:]        = 0.0
383
            train1 [0]        = 1.0 if cclass>=0 or len(classes)==0 else 0.0 ###########!!!!!!!!!!!!!!!!!! 2019-08-08
384
            train1 [1:5]      = lx4
385
            if (len(classes)>0 and cclass>=0) : 
386
                train1 [5+cclass] = 1.0
387
                #print(iinn,tc[1],tc[0],ian)
388

389
            ianNew = ian
390
            try :
391
                while ytrain[ii,tc[1],tc[0],ianNew,0]==1.0 :
392
                    ianNew = (ianNew+1) % n_anchors
393
                    if ian==ianNew : break
394

395
                if ytrain[ii,tc[1],tc[0],ianNew,0]==1.0 :
396
                    cc2 = cc2 + 1
397
                    ii2 = ii2 + 1
398

399
            except :
400
                if  printOK :
401
                    print('except: ', ii, tc[1], tc[0], ianNew)
402
                    print('lx5 ',lx5)
403
                    print('lx4 ',lx4)
404
                    print('in:',shape_in)
405
                    print(lx4[0]*shape_net[1],lx4[1]*shape_net[0])
406
                    print(np.array(shape_net)/np.array(shape_in[:2]))
407

408
            ytrain[iinn,tc[1],tc[0],ianNew,:] = train1
409
            
410
    return (ytrain, (cc1,cc2,cc3))
411

412
###############################################################################################
413

414
def yTrainCreate3(subTrain5, classes, shape_net, shape_out, anchorsl, 
415
                  train_scale, train_shape_in,
416
                  debug=False,
417
                  printOK=False) :
418

419
    ##assert(type(subTrain5)==type(np.array(np.zeros((1,)))))
420
    assert(len(subTrain5)==len(train_scale))
421
    assert(len(subTrain5)==len(train_shape_in))
422
    
423
    ii = -100
424
    
425
    n_anchors = len(anchorsl)
426
    array_size= len(subTrain5)
427

428
    ytrain    = np.zeros([array_size,]+list(shape_out), dtype=np.float32)
429

430
    train10   = np.zeros((5+len(classes)), dtype=np.float32)
431
    
432
    grid_net  = (shape_net[0]/shape_out[0],shape_net[1]/shape_out[1])
433

434
    cc1, cc2  =  0, 0
435

436
    for iinn, (ll,scale,shape_in) in enumerate(zip(subTrain5,train_scale,train_shape_in)) :
437
        
438
        anmax =  anchorsl
439

440
        ii1, ii2   =  0, 0
441

442
        lx5sort    =  np.array(ll.split()).reshape((-1,5))
443
        temp       =  (lx5sort[:,3]).astype(float)*lx5sort[:,4].astype(float)
444
        
445
        for lx5 in lx5sort[temp.argsort()] :
446

447
            # x,y,w,h - x columns, y rows
448
            lx4      = lx5[1:].astype(float)
449

450
            cclass = -1
451

452
            if len(classes)>0 :
453
                try    : cclass = classes.tolist().index(lx5[0])
454
                except : cclass = -1
455

456
            cc1 = cc1 + 1
457
            ii1 = ii1 + 1
458

459
            lx2max     =  lx5[3:].astype(np.float32)*scale
460
            temp       =  np.array([np.minimum(lx2max,anmax[jj]) for jj in range(len(anmax))])
461
            temp       =  temp[:,0]*temp[:,1]
462
            iou        =  temp/(np.add(anmax[:,0]*anmax[:,1],lx2max[0]*lx2max[1])-temp)
463

464
            ian        =  np.argmax(iou)
465
            
466
            lx4[0:2]   =  ((lx4[:2]+lx4[2:]/2)*scale)
467
            lx4[2:4]   =  (lx4[2:4]*scale)
468
            
469
            lx4[0:2]   =  np.clip(lx4[0:2],0.0,(shape_net[1],shape_net[0]))
470
            
471
            center_col_row    =  np.clip((lx4[0:2]/(grid_net[1],grid_net[0])).astype(int),
472
                                         0,(shape_out[1]-1,shape_out[0]-1))
473

474
            lx4[[0,2]] =  lx4[[0,2]]/shape_net[1]
475
            lx4[[1,3]] =  lx4[[1,3]]/shape_net[0]
476
            
477
            train1            = train10.copy().astype(float)
478
            train1 [0]        = 1.0 if cclass>=0 or len(classes)==0 else 0.0 ###########!!!!!!!!!!!!!!!!!! 2019-08-08
479
            train1 [1:5]      = lx4
480
            if (len(classes)>0 and cclass>=0) : 
481
                train1 [5+cclass] = 1.0
482

483
            ianNew = ian
484
            try :
485
                while ytrain[iinn,center_col_row[1],center_col_row[0],ianNew,0]==1.0 :
486
                    ianNew = (ianNew+1) % n_anchors
487
                    if ian==ianNew : break
488

489
                if ytrain[iinn,center_col_row[1],center_col_row[0],ianNew,0]==1.0 :
490
                    cc2 = cc2 + 1
491
                    ii2 = ii2 + 1
492

493
            except :
494
                if  printOK :
495
                    print('except: ', iinn, tc[1], tc[0], ianNew)
496
                    print('lx5 ',lx5)
497
                    print('lx4 ',lx4)
498
                    print('in:',shape_in)
499
                    print(lx4[0]*shape_net[1],lx4[1]*shape_net[0])
500
                    print(np.array(shape_net)/np.array(shape_in[:2]))
501
                    
502
            if  ytrain[iinn,center_col_row[1],center_col_row[0],ianNew,0]==0.0 :
503
                ytrain[iinn,center_col_row[1],center_col_row[0],ianNew,:] = train1
504
            
505
    if debug : return (ytrain, (cc1,cc2))
506
    return ytrain
507

508
###############################################################################################
509

510
def drawTrain1(img1, ytrain1, shape_net, iiNumber=-1, show=True ) :
511

512
    if show : plt.figure(figsize=(10,15))
513
    plt.imshow(img1.squeeze())
514

515
    iCount, rCount = 0, 0
516
    for rr, a1 in enumerate(ytrain1) :
517
        for cc, a2 in enumerate(a1) :
518
            for aa, a4 in enumerate(a2) :
519
                if a4[0]>0.5 :
520
                    iCount +=1
521
                    #print(len(pp), ii, rr, cc, aa, pp[0], np.round(pp[1:5],4),shape_net)
522
                    
523
                    lx4 = a4[1:5].copy()
524
                    lx4[[0,2]], lx4[[1,3]] = lx4[[0,2]]*shape_net[1], lx4[[1,3]]*shape_net[0]
525
                    tl, dr = np.floor(lx4[0:2]-lx4[2:4]/2), np.ceil(lx4[0:2]+lx4[2:4]/2)
526
                    
527
                    tl = np.clip(tl,0,(shape_net[1],shape_net[0]))
528
                    dr = np.clip(dr,0,(shape_net[1],shape_net[0]))
529
                    
530
                    #print(len(pp), ii, rr, cc, aa, pp[0], np.round(pp[1:5],4),tl,dr,lx4)
531
                    
532
                    class1, color = -1, 'r'
533
                    try :
534
                        class1 = a4[5:].argmax()
535
                        color  = 'r' if a4[5+class1]>0.5 else 'b'
536
                        if color=='r' : 
537
                            #print(lx4)
538
                            rCount = rCount+1
539
                    except : 
540
                        class1, color = -1, 'r'
541
                    finally :
542
                        #print(lx4,class1,color)
543
                        plt.scatter(lx4[0],lx4[1], c=color)
544
                    
545
                    border = [tl,[tl[0],dr[1]],dr,[dr[0],tl[1]]]
546
                    #print(lx4)
547
                    #print(border)
548
                    line = plt.Polygon(border, closed=True, fill=None, edgecolor=color)
549
                    plt.gca().add_line(line)
550
                    
551

552
    plt.title(str(iCount)+' '+str(rCount))
553
    plt.title(str(iCount)+' '+str(rCount)+(' ('+str(iiNumber)+')' if iiNumber>=0 else ''))
554
    
555
    if show :
556
        plt.show()
557
        plt.close()
558
        print(iCount)
559
    return
560
    
561
#drawTrain1 (xtrain[0],ytrain[0])
562

563
###############################################################################################
564

565
def drawPred1 (img1, pred1, anchors, grid_net, shape_net, threshold=0.5, 
566
               iiNumber=-1, f1=-1,
567
               sigmoidOK=True, show=True, printOK=False) :
568
    
569
    if show : plt.figure(figsize=(10,15))
570
    plt.imshow(img1.squeeze())
571
    
572
    iCount, rCount = 0, 0
573
    
574
    ecolor = ['r','g','b','w']
575

576
    for rr, a1 in enumerate(pred1) :
577
        for cc, a2 in enumerate(a1) :
578
            for aa, pr in enumerate(a2) :
579
                if s(pr[0])>=threshold :
580
                    iCount = iCount + 1
581
                    lx4 = pr[1:5].copy()
582
                    if sigmoidOK : lx4[0:2] = s(lx4[0:2])
583
                    
584
                    #print(lx4[0:2],rr,cc,grid_net)
585
                    lx4[0:2] = np.round((lx4[0:2]+np.array((cc,rr)))*(grid_net[1],grid_net[0])) # x, y
586
                    #print(lx4[0:2])
587
                    
588
                    pclass   = -1
589
                    if len(pr)>5 :
590
                        aacc   = s(pr[5:])
591
                        iclass = aacc.argmax()
592
                        pclass = aacc[iclass]
593
                    marker = 'o' if pclass>0.5 else 's'
594
                    color  = 'r' if pclass>0.5 else 'b'
595
                    if color=='r' : rCount = rCount+1
596
                    if len(pr)<=5 :
597
                        marker = 'o'
598
                        color  = 'r'
599
                    
600
                    plt.scatter(lx4[0],lx4[1], color=color, marker=marker)
601
                    
602
                    lx4[2:4] = np.exp(lx4[2:4])*anchors[aa] # w,h
603
                    
604
                    tl, dr = np.floor(lx4[0:2]-lx4[2:4]/2), np.ceil(lx4[0:2]+lx4[2:4]/2)
605
                    
606
                    tl[0]  = np.clip(tl[0],0,shape_net[1])
607
                    tl[1]  = np.clip(tl[1],0,shape_net[0])
608
                    dr[0]  = np.clip(dr[0],0,shape_net[1])
609
                    dr[1]  = np.clip(dr[1],0,shape_net[0])
610
                    
611
                    border = [tl,[tl[0],dr[1]],dr,[dr[0],tl[1]]]
612
                    line   = plt.Polygon(border, closed=True, fill=None, edgecolor=ecolor[aa]) #'r')
613
                    plt.gca().add_line(line)
614

615
                    
616
    plt.title(str(iCount)+' '+str(rCount)+
617
              (' ('+str(iiNumber)+')' if iiNumber>=0 else '')+(' ('+str(f1)+')' if f1>=0 else ''))
618
    
619
    if show :
620
        plt.show()
621
        plt.close()
622
        print(iCount)
623
        
624
    return

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.