Marthee commited on
Commit
1d05f23
·
1 Parent(s): 67709af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +353 -54
app.py CHANGED
@@ -1,58 +1,357 @@
1
- import copy_of_xorPileCaps
2
- # copy_of_xorPileCaps.Pick
3
-
4
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
 
 
 
6
 
7
- with gr.Blocks() as mainBlock:
8
- # def switch(s: int):
9
- # """Textbox visibility is turned off when s = 0, and is on otherwise."""
10
- # return gr.ColorPicker.update(visible=True)
11
- with gr.Row():
12
- out1=0
13
- with gr.Column():
14
- # inputs0 = [
15
- in1=gr.Image(label="icon", type="pil", image_mode="RGBA")
16
- # gr.Textbox(label="Number of Levels"),
17
- # gr.ColorPicker(label="color"),
18
- in2=gr.Radio(label="Measurement",choices=["Measure Full Image", "Measure Specified Regions"])
19
- in3=gr.Radio(label="Area or Perimeter",choices=["Area", "Perimeter"])
20
- with gr.Row():
21
- in4=gr.ColorPicker(label="color" )
22
- in5=gr.ColorPicker(label="color" )
23
- in6=gr.ColorPicker(label="color" )
24
- in7=gr.ColorPicker(label="color" )
25
- in8=gr.ColorPicker(label="color" )
26
- in9=gr.ColorPicker(label="color" )
27
- in10=gr.ColorPicker(label="color" )
28
- in11=gr.ColorPicker(label="color" )
29
- # updating a should update o
30
- # a's visibility depends on s
31
- # in4.change(switch, , a)
32
-
33
-
34
- with gr.Column():
35
- out1 = gr.Image(label="Image", type="pil", image_mode="RGBA")
36
- #gr.Dataframe(label='Dictionary' ), # row_count = (5, "fixed")
37
- # ]
38
- btn1 = gr.Button("Submit")
39
-
40
-
41
- with gr.Row():#(visible=False) as output_col:
42
- # def submit(in1, in2, in3):
43
- # drawnimg=PickColorContours(in1,in2,in3)
44
- # return drawnimg, { output_col: gr.update(visible=True) }
45
- with gr.Column():
46
- num1=gr.Number(label='Real value')
47
- num2=gr.Number(label='Pixel value')
48
- dp=gr.Dropdown(["m", "cm", "mm"])
49
- btn = gr.Button("Submit Ratio")
50
- with gr.Column():
51
- outputs1 = [
52
- gr.Image(label="Image", type="pil", image_mode="RGBA"),
53
- gr.Dataframe(label='Dictionary' ), # row_count = (5, "fixed")
54
- ]
55
- btn1.click(fn=PickColorContours, inputs=[dp,in1,in2,in3,in4,in5,in6,in7,in8,in9,in10,in11], outputs=out1)
56
- btn.click(fn=PickColorContours, inputs=[dp,in1,in2,in3,in4,in5,in6,in7,in8,in9,in10,in11,num1,num2], outputs=outputs1)
57
 
58
- mainBlock.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
 
3
  import gradio as gr
4
+ import fitz
5
+ import pandas as pd
6
+ from PIL import Image
7
+ import os
8
+ from db import dropbox_upload_file
9
+ from pathlib import Path
10
+ from PreprocessingFoundation import rmv_text,rmv_dashedLines
11
+
12
+ #############################################################################################
13
+
14
+ '''push output to dropbox'''
15
+ #os.remove('dropbox_plans/Trees.pdf')
16
+
17
+
18
+ def pushToDropbox(plan1,area,perim,df):
19
+ plan=Path(os.path.split(plan1)[1]).stem
20
+ p=dropbox_upload_file('.',local_file=perim,dropbox_file_path='/savedMeasurements/'+plan+'perim.png')
21
+ a=dropbox_upload_file('.',local_file=area,dropbox_file_path='/savedMeasurements/'+plan+'area.png')
22
+ d=dropbox_upload_file('.',local_file=df,dropbox_file_path='/savedMeasurements/'+plan+'summary.csv')
23
+ #print(f)
24
+
25
+ def auth(username,password):
26
+ if username=="alaa" and password=="1234":
27
+ return True
28
+
29
+
30
+
31
+ ############################################################################################
32
+
33
+ def plan2img(plan):
34
+ if 'foundation' in plan.lower():
35
+ noTextImg=rmv_text(plan)
36
+ clean_img=rmv_dashedLines(noTextImg)
37
+ return clean_img
38
+
39
+ else:
40
+ fname = plan
41
+ #op='pictures/found.png'
42
+ doc = fitz.open(fname) # open document
43
+ for page in doc:
44
+ pix = page.get_pixmap() # render page to an image
45
+ pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
46
+ pl1=np.array(pl)
47
+ return pl1
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+ ##################################################################################################3
56
+
57
+ def detectCircles(imagesliced ):
58
+ copy=imagesliced.copy()
59
+ imgGry1 = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
60
+ gray_blurred = cv2.medianBlur(imgGry1, 1)
61
+ # gray_blurred = cv2.blur(imgGry1, (9,9 ))
62
+ kernel=np.ones((2,2),np.uint8)
63
+ er1=cv2.erode(gray_blurred,kernel, iterations=3)
64
+ # Apply Hough transform on the blurred image.
65
+ # min distance between circles, Upper threshold for the internal Canny edge detector.
66
+ detected_circles = cv2.HoughCircles( er1, cv2.HOUGH_GRADIENT, 1, 100, param1 = 300,
67
+ param2 = 16, minRadius = 15, maxRadius = 50) #18 param2
68
+
69
+ # Draw circles that are detected.
70
+ if detected_circles is not None:
71
+ # Convert the circle parameters a, b and r to integers.
72
+ detected_circles = np.uint16(np.around(detected_circles))
73
+ detected_circles = np.round(detected_circles[0, :]).astype("int")
74
+
75
+ for (x, y, r) in detected_circles:
76
+ cv2.circle(copy, (x, y), r, (0, 255, 0), 4)
77
+ # cv2_imshow(copy)
78
+ if detected_circles is not None:
79
+ return len(detected_circles)
80
+
81
+
82
+ ''' call if pile caps plans are chosen'''
83
+ def PileCaps(img):
84
+
85
+ imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
86
+ blur = cv2.medianBlur(imgGry, 3)
87
+ kernel=np.ones((3,4),np.uint8)
88
+ er2=cv2.dilate(blur,kernel, iterations=2)
89
+ ret3, thresh = cv2.threshold(er2, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
90
+
91
+ imgArea= img.copy()
92
+ imgPerimeter=img.copy()
93
+ imgtransparent=img.copy()
94
+
95
+ imgHeight,imgWidth,_=img.shape
96
+ count1=0
97
+ count2=0
98
+ count3=0
99
+ count4=0
100
+ count5=0
101
+ count6=0
102
+
103
+ Array1area=[]
104
+ Array2area=[]
105
+ Array3area=[]
106
+ Array4area=[]
107
+ Array5area=[]
108
+ Array6area=[]
109
+
110
+ Array1Perimeter=[]
111
+ Array2Perimeter=[]
112
+ Array3Perimeter=[]
113
+ Array4Perimeter=[]
114
+ Array5Perimeter=[]
115
+ Array6Perimeter=[]
116
+
117
+
118
+ #getcontours
119
+ contours , hier = cv2.findContours(thresh , mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)
120
+ for contour in contours:
121
+ area = cv2.contourArea(contour)
122
+ perimeter = cv2.arcLength(contour, True)
123
+ x, y , width, height = cv2.boundingRect(contour)
124
+ if area > 1500 :# and height > 50:
125
+ approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour, True), True)
126
+ # cv2.drawContours(imgArea, [contour], 0, (0, 0, 255), 5)
127
+ # cv2.drawContours(imgPerimeter, [contour], 0, (0, 0, 255), 10)
128
+
129
+ aspectRatio= float(width) / height
130
+ imagesliced = imgArea[ y:y+height , x:x+width ]
131
+ circles=detectCircles(imagesliced)
132
+ if len(approx) >= 4 and len(approx) <= 8:
133
+ # if aspectRatio >=0.9 and aspectRatio <= 1.1:
134
+ if circles == 1:
135
+ count1+=1
136
+ cv2.drawContours(imgArea, [contour], 0, (240, 213, 175), -1 )
137
+ cv2.drawContours(imgPerimeter, [contour], 0, (240, 213, 175), 3 )
138
+ Array1area.append(area)
139
+ Array1Perimeter.append(perimeter)
140
+ elif circles == 2:
141
+ count2+=1
142
+ cv2.drawContours(imgArea, [contour], 0, (50, 200, 20), -1 )
143
+ cv2.drawContours(imgPerimeter, [contour], 0, (50, 200, 20), 3 )
144
+ Array2area.append(area)
145
+ Array2Perimeter.append(perimeter)
146
+ elif circles == 3:
147
+ count3+=1
148
+ cv2.drawContours(imgArea, [contour], 0, (0, 150, 255), -1 )
149
+ cv2.drawContours(imgPerimeter, [contour], 0, (0, 150, 255), 3 )
150
+ Array3area.append(area)
151
+ Array3Perimeter.append(perimeter)
152
+ elif circles ==4:
153
+ count4+=1
154
+ cv2.drawContours(imgArea, [contour], 0, (240, 213, 0), -1 )
155
+ cv2.drawContours(imgPerimeter, [contour], 0, (240, 213, 0), 3)
156
+ Array4area.append(area)
157
+ Array4Perimeter.append(perimeter)
158
+ elif circles==5:
159
+ count5+=1
160
+ cv2.drawContours(imgArea, [contour], 0, (200, 20, 100), -1 )
161
+ cv2.drawContours(imgPerimeter, [contour], 0, (200, 20, 100), 3 )
162
+ Array5area.append(area)
163
+ Array5Perimeter.append(perimeter)
164
+ elif circles==6:
165
+ count6+=1
166
+ cv2.drawContours(imgArea, [contour], 0, (240, 0, 0), -1 )
167
+ cv2.drawContours(imgPerimeter, [contour], 0, (240, 0, 0), 3 )
168
+ Array6area.append(area)
169
+ Array6Perimeter.append(perimeter)
170
+ else:
171
+ cv2.putText(imgArea,str(len(approx)), (x+20,y-20) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,128), 2)
172
+ cv2.drawContours(imgArea, [contour], 0, (180, 100, 0), -1 )
173
+ cv2.drawContours(imgPerimeter, [contour], 0, (180, 100, 0), 3 )
174
+ else:
175
+ cv2.putText(imgArea,str(len(approx)), (x+20,y-20) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,128), 2)
176
+ cv2.drawContours(imgArea, [contour], 0, (180, 100, 200), -1 )
177
+ cv2.drawContours(imgPerimeter, [contour], 0, (180, 100, 200), 3 )
178
+
179
+ alpha = 0.4 # Transparency factor.
180
+ image_new = cv2.addWeighted(imgArea, alpha, imgtransparent, 1 - alpha, 0)
181
+
182
+ cv2.putText(imgArea,'Area= ' + str(area) + ' px', (x+50,y-50) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,128), 2)
183
+ cv2.putText(imgPerimeter,'Perimeter= '+str(round(perimeter, 2)) + ' px', (x+50,y-50) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
184
+
185
+ #dataframe for counts, areas, perimeter
186
+ data = {'Number of Piles':['1','2','3','4','5','6'],'Count': [count1,count2,count3,count4,count5,count6], 'Areas' : [avg(Array1area),avg(Array2area),avg(Array3area),avg(Array4area),avg(Array5area),avg(Array6area)], 'Perimeter': [avg(Array1Perimeter), avg(Array2Perimeter), avg(Array3Perimeter), avg(Array4Perimeter), avg(Array5Perimeter),avg(Array6Perimeter)] }
187
+ df= pd.DataFrame(data)
188
+
189
+ return image_new, imgPerimeter, df
190
+
191
+
192
+ ''' call if foundation plans are chosen'''
193
+ def IsolatedFoundations(img1):
194
+ img=cv2.cvtColor(img1, cv2.COLOR_RGB2BGR)
195
+ arrayAreaSquares=[]
196
+ arrayAreaGB1=[]
197
+ arrayAreaGB2=[]
198
+
199
+ arrayPerimeterSquares=[]
200
+ arrayPerimeterGB1=[]
201
+ arrayPerimeterGB2=[]
202
+
203
 
204
+ countSquares=0
205
+ countGB1=0
206
+ countGB2=0
207
 
208
+ #preprocessing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
+ imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
211
+ blur = cv2.medianBlur(imgGry,1)
212
+ kernel = np.array([[1,4,6,4,1], [4,16,24,16,4], [6,24,-476,24,6],[4,16,24,16,4],[1,4,6,4,1]]) * (-1/256) #unsharp masking kernel
213
+ sharpen = cv2.filter2D(blur, -1, kernel)
214
+ eroded = cv2.erode(sharpen, kernel,iterations =4)
215
+ dilated= cv2.dilate(eroded, kernel, iterations= 4)
216
+ kernel1 = np.array([[1,4,6,4,1], [4,16,24,16,4], [6,24,-476,24,6],[4,16,24,16,4],[1,4,6,4,1]]) * (-1/256) #unsharp masking kernel
217
+ sharpen1 = cv2.filter2D(dilated, -1, kernel1)
218
+ ret, thresh = cv2.threshold(sharpen1, 195, 255, cv2.THRESH_BINARY)
219
+
220
+ #getContours
221
+ contours , hier = cv2.findContours(thresh , mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_NONE)
222
+
223
+ #drawContours
224
+ imgArea= img.copy()
225
+ imgPerimeter=img.copy()
226
+
227
+ for contour in contours:
228
+ x, y , width, height = cv2.boundingRect(contour)
229
+ area = cv2.contourArea(contour)
230
+ # perimeter = cv2.arcLength(contour, True)
231
+ perimeter=round(cv2.arcLength(contour, True),2)
232
+ aspectRatio = float(width)/height
233
+ #GB1
234
+ if (height >= 70 and height <= 90 ) or (width >=70 and width <=90):
235
+ if aspectRatio >= 0.9 and aspectRatio <= 1.1 :
236
+ continue
237
+ else:
238
+ countGB1+=1
239
+ cv2.drawContours(imgArea, [contour], 0, (221, 160, 221), 2)
240
+ cv2.drawContours(imgPerimeter, [contour], 0, (221, 160, 221), 2)
241
+ cv2.putText(imgArea,'Area= ' + str(area) + ' px', (x+20,y+30) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (221, 160, 221), 2)
242
+ cv2.putText(imgPerimeter,('Perimeter=' + str(perimeter)+ ' px'), (x,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
243
+ arrayAreaGB1.append(area)
244
+ arrayPerimeterGB1.append(perimeter)
245
+ #GB2 - red
246
+ if area > 1700 and area < 1000000 :
247
+ if (height >= 70 and height <= 90 ) or (width >=70 and width <=90):
248
+ continue
249
+ else:
250
+ if height > 1020 or width <150:
251
+ if aspectRatio >= 0.9 and aspectRatio <= 1.1 :
252
+ continue
253
+ else:
254
+ countGB2+=1
255
+ cv2.drawContours(imgArea, [contour], 0, (0,0,255), 2)
256
+ cv2.drawContours(imgPerimeter, [contour], 0, (0, 0, 255), 2)
257
+ cv2.putText(imgArea,'Area=' + str(area) + ' px', (x+20,y+30) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
258
+ cv2.putText(imgPerimeter,('Perimeter=' + str(perimeter) + ' px'), (x,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
259
+ arrayAreaGB2.append(area)
260
+ arrayPerimeterGB2.append(perimeter)
261
+
262
+ #squares - blue
263
+ if (area > 2200 ):
264
+ approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour, True), True)
265
+ if len(contour) >= 4:
266
+ sqarea= float(width)*float(height)
267
+
268
+ if aspectRatio >= 0.95 and aspectRatio <= 1.05 :
269
+ countSquares+=1
270
+ cv2.rectangle(imgArea, (x, y), (x + width, y + height), (255,0,0), 2) # square blue
271
+ cv2.putText(imgArea,'Area= '+ str(sqarea) + ' px', (x+20,y+30) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
272
+ cv2.rectangle(imgPerimeter, (x, y), (x + width, y + height), (255,0,0), 2) # square blue
273
+ cv2.putText(imgPerimeter,('Perimeter=' + str(perimeter) + ' px'), (x,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
274
+ arrayAreaSquares.append(area)
275
+ arrayPerimeterSquares.append(perimeter)
276
+
277
+ #dataframe for counts, areas, perimeter
278
+ data = {'Type':['Isolated Foundations', 'GB1' , 'GB2'],'Count': [countSquares,countGB1,countGB2], 'Areas' : [avg(arrayAreaSquares),avg(arrayAreaGB1),avg(arrayAreaGB2)], 'Perimeter': [avg(arrayPerimeterSquares), avg(arrayPerimeterGB1), avg(arrayPerimeterGB2)] }
279
+ df= pd.DataFrame(data)
280
+
281
+ return imgArea,imgPerimeter,df
282
+
283
+
284
+ def avg(arr):
285
+ if len(arr)==0:
286
+ return round(sum(arr),2)
287
+ return round(sum(arr)/ len(arr),2)
288
+
289
+
290
+
291
+ ''' General measurement function'''
292
+ def getMeasurement(plan,SaveOP):
293
+ if plan==None:
294
+ area,perim,df=None,None,None
295
+ elif 'foundation' in plan:
296
+ plan1='dropbox_plans/'+str(plan)
297
+ img=plan2img(plan1)
298
+ area,perim,df=IsolatedFoundations(img)
299
+ #area,perim,df=img,None,None
300
+ elif 'piles' or 'pc' in plan: #any pile cap
301
+ plan1='dropbox_plans/'+str(plan)
302
+ img=plan2img(plan1)
303
+ area,perim,df=PileCaps(img)
304
+ if SaveOP:
305
+ pushToDropbox(plan,area,perim,df)
306
+
307
+ return area,perim,df
308
+ ##########################################################
309
+ def update_dropdown(project):
310
+
311
+ plans_inrepo=os.listdir('dropbox_plans')
312
+ #if 'foundation' in radio and project in plans_inrepo
313
+ matches=[]
314
+ if project==None:
315
+ drop=gr.Dropdown.update(choices=matches)
316
+ else:
317
+ for x in plans_inrepo:
318
+ if (project in x): #project name and section in a plan
319
+ matches.append(x)
320
+ drop=gr.Dropdown.update(choices=matches)
321
+
322
+ return drop
323
+
324
+ ######################################################################################
325
+ def clear(demo):
326
+ return None,None,None,None
327
+
328
+
329
+
330
+
331
+
332
+
333
+ #############################################################################################################################3
334
+ with gr.Blocks(css="#search {background: orangered}") as demo:
335
+ with gr.Row():
336
+ with gr.Column():
337
+ project=gr.Dropdown(choices=['BMW job1','BMW job2','Project C'],interactive=True,label='Projects')
338
+ drop=gr.Dropdown(choices=None,interactive=True,label='project parts')
339
+ radio_button = gr.Dropdown(choices=['foundation','external','interior'], value=None, interactive=True,label='sections')
340
+
341
+ check=gr.Checkbox(label='SaveOutput')
342
+ show_button = gr.Button(value="Measure",elem_id='search')
343
+ clr_btn=gr.Button(value='Clear')
344
+ with gr.Column():
345
+ img1=gr.Image()
346
+ img2=gr.Image()
347
+ df=gr.Dataframe()
348
+
349
+
350
+
351
+
352
+
353
+ show_button.click(fn=getMeasurement,inputs=[drop,check],outputs=[img1,img2,df])
354
+ clr_btn.click(fn=clear,outputs=[project,radio_button,check,drop])
355
+ project.change(fn=update_dropdown, inputs=[project], outputs=drop)
356
+ demo.launch(debug=True)
357
+