Marthee commited on
Commit
1070671
·
verified ·
1 Parent(s): 8392676

Update doors_fasterrcnn.py

Browse files
Files changed (1) hide show
  1. doors_fasterrcnn.py +189 -27
doors_fasterrcnn.py CHANGED
@@ -71,7 +71,7 @@ def get_model(num_classes):
71
 
72
  return model
73
 
74
- def ev_model(img, model, device, threshold):
75
  image_tensor = F.to_tensor(img).unsqueeze(0)
76
  image_tensor = image_tensor.to(device)
77
  model.eval()
@@ -89,9 +89,159 @@ def ev_model(img, model, device, threshold):
89
  else:
90
  double_boxes.append(predictions[0]['boxes'][element].tolist())
91
 
92
- return single_boxes, double_boxes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- def calculate_width(bbox):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  #if looking right or left, width < height
96
  bbox_width = bbox[2] - bbox[0]
97
  bbox_height = bbox[3] - bbox[1]
@@ -100,8 +250,8 @@ def calculate_width(bbox):
100
  else:
101
  door_width = bbox_height
102
  return door_width
103
-
104
- def width_annotations(bbox, ratio):
105
  lines = []
106
  width = []
107
 
@@ -122,23 +272,23 @@ def width_annotations(bbox, ratio):
122
  x = (x1+x1)/2
123
  y = (y1+y2)/2
124
  width.append(((x,y), door_width))
125
- return lines, width
126
 
127
- def create_width_annotations(width_info):
128
  annotations = []
129
  for i in range(len(width_info)):
130
  annotations.append(((width_info[i][0][0]),(width_info[i][0][1]),f"{width_info[i][1]} m"))
131
- return annotations
132
 
133
- def calculate_midpoint(top_left, bottom_right):
134
  x1, y1 = top_left
135
  x2, y2 = bottom_right
136
  # Calculate the midpoint
137
  xm = int((x1 + x2) / 2)
138
  ym = int((y1 + y2) / 2)
139
- return (xm, ym)
140
 
141
- def mid_points_bbox(bbox):
142
  midpoint = []
143
  for i in range(len(bbox)):
144
  x1 = int(bbox[i][0])
@@ -148,9 +298,9 @@ def mid_points_bbox(bbox):
148
  top_left_corner = (x1, y1)
149
  bottom_right_corner = (x2, y2)
150
  midpoint.append(calculate_midpoint(top_left_corner, bottom_right_corner))
151
- return midpoint
152
 
153
- def create_annotations(door_kind, midpoints):
154
  door = door_kind
155
  annotations = []
156
  for i in range(len(midpoints)):
@@ -220,13 +370,13 @@ def add_annotations_to_pdf(image, pdf_name, annotation_s, annotation_d,width_ann
220
  return pdf_document
221
  # pdf_document.save(output_pdf_path)
222
  # pdf_document.close()
223
-
224
  def main_run(pdf_fullpath, weights_path, pdf_name,pdfpath,ratio): ####pdf_fullpath here is the data and not the path
225
  img_pillow = convert2pillow(pdf_fullpath)
226
  #new_image = img_pillow.resize((2384, 1684))
227
 
228
  # Specify the number of classes (including the background)
229
- num_classes = 3 # Ensure this matches the saved model's number of classes
230
 
231
  # Load the model with the specified number of classes
232
  model = get_model(num_classes)
@@ -247,27 +397,37 @@ def main_run(pdf_fullpath, weights_path, pdf_name,pdfpath,ratio): ####pdf_fullpa
247
  model.to(device)
248
 
249
  # START INFERENCE
250
- sbox, dbox = ev_model(img_pillow, model, device, 0.6)
251
 
252
  #Dataframe for Doors count
253
- doors_count = {'Type': ['Single Doors', 'Double Doors'], 'Quantity': [len(sbox), len(dbox)]}
254
- df_doors = pd.DataFrame(doors_count)
255
 
256
- single_midpoint = mid_points_bbox(sbox)
257
- double_midpoint = mid_points_bbox(dbox)
258
 
259
  #Kind Annotations
260
- single_annotations = create_annotations("single door", single_midpoint)
261
- double_annotations = create_annotations("double door", double_midpoint)
262
  #Lines Annotations
263
- line_single, width_signle = width_annotations(sbox, 1)
264
- line_double, width_double = width_annotations(dbox, 1)
265
  #Width Annotations
266
- width_single_ann = create_width_annotations(width_signle)
267
- width_double_ann = create_width_annotations(width_double)
268
 
269
  # add_annotations_to_pdf(new_image, pdf_name, single_annotations, double_annotations)
270
- pdf_document=add_annotations_to_pdf(img_pillow, pdf_name, single_annotations, double_annotations,width_single_ann,width_double_ann,line_single,line_double)
 
 
 
 
 
 
 
 
 
 
271
 
272
  page=pdf_document[0]
273
  pix = page.get_pixmap() # render page to an image
@@ -282,6 +442,8 @@ def main_run(pdf_fullpath, weights_path, pdf_name,pdfpath,ratio): ####pdf_fullpa
282
  for annot in page.annots():
283
  list1.loc[len(list1)] =annot.info
284
 
 
 
285
  return annotatedimg, pdf_document , spreadsheet_url, list1 , df_doors
286
 
287
  # model_path = '/content/drive/MyDrive/combined.pth'
 
71
 
72
  return model
73
 
74
+ '''def ev_model(img, model, device, threshold):
75
  image_tensor = F.to_tensor(img).unsqueeze(0)
76
  image_tensor = image_tensor.to(device)
77
  model.eval()
 
89
  else:
90
  double_boxes.append(predictions[0]['boxes'][element].tolist())
91
 
92
+ return single_boxes, double_boxes'''
93
+
94
+ def ev_model(img, model, device, threshold):
95
+ image_tensor = F.to_tensor(img).unsqueeze(0)
96
+ image_tensor = image_tensor.to(device)
97
+ model.eval()
98
+
99
+ with torch.no_grad():
100
+ predictions = model(image_tensor)
101
+
102
+ doors_info = []
103
+ for element in range(len(predictions[0]['boxes'])):
104
+ score = predictions[0]['scores'][element].item()
105
+ if score > threshold:
106
+ box = predictions[0]['boxes'][element].tolist()
107
+ label = predictions[0]['labels'][element].item()
108
+ doors_info.append((box,label))
109
+ return doors_info
110
+
111
+
112
+ def distance(point1, point2):
113
+ x1, y1 = point1
114
+ x2, y2 = point2
115
+ return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
116
+
117
+ def calculate_midpoint(p1, p2):
118
+ x1, y1 = p1
119
+ x2, y2 = p2
120
+ # Calculate the midpoint
121
+ xm = int((x1 + x2) / 2)
122
+ ym = int((y1 + y2) / 2)
123
+ return (xm, ym)
124
+ def get_door_info(doors_info):
125
+ width_pixels = []
126
+ lines = []
127
+ sanda = []
128
+ line_midpoint = []
129
+ for door_inf in doors_info:
130
+ xmin, ymin, xmax, ymax = door_inf[0]
131
+ #horz_bottom
132
+ if door_inf[1] == 2:
133
+ #for drawing
134
+ point_st = (int(xmin), int(ymax) + 5)
135
+ point_end = (int(xmax),int(ymax) + 5)
136
+ lines.append((point_st,point_end))
137
+
138
+ sanda_st = (int(xmin), int(ymax))
139
+ sand_end = (int(xmax),int(ymax))
140
+ sanda.append((sanda_st, sand_end))
141
+
142
+ line_midpoint.append(calculate_midpoint(sanda_st,sand_end))
143
+ #for calculation
144
+ width = distance((xmin,ymax), (xmax,ymax))
145
+ width_pixels.append(width)
146
+
147
+ #horz_upper
148
+ if door_inf[1] == 3:
149
+ #for drawing
150
+ point_st = (int(xmin),int(ymin) -5)
151
+ point_end = (int(xmax),int(ymin) - 5)
152
+ lines.append((point_st,point_end))
153
+
154
+ sanda_st = (int(xmin),int(ymin))
155
+ sand_end = (int(xmax),int(ymin))
156
+ sanda.append((sanda_st, sand_end))
157
+ line_midpoint.append(calculate_midpoint(sanda_st,sand_end))
158
+ #for calculation
159
+ width = distance((xmin,ymin), (xmax,ymin))
160
+ width_pixels.append(width)
161
+
162
+ #vert_right
163
+ if door_inf[1] == 4:
164
+ #for drawing
165
+ point_st = (int(xmax) + 5,int(ymin))
166
+ point_end = (int(xmax) + 5,int(ymax))
167
+ lines.append((point_st,point_end))
168
+
169
+ sanda_st = (int(xmax), int(ymin))
170
+ sand_end = (int(xmax), int(ymax))
171
+ sanda.append((sanda_st, sand_end))
172
+ line_midpoint.append(calculate_midpoint(sanda_st,sand_end))
173
+ #for calculation
174
+ width = distance((xmax,ymin), (xmax,ymax))
175
+ width_pixels.append(width)
176
+ #vert_left
177
+ if door_inf[1] == 5:
178
+ #for drawing
179
+ point_st = (int(xmin) -5,int(ymin))
180
+ point_end = (int(xmin) -5,int(ymax))
181
+ lines.append((point_st,point_end))
182
+
183
+ sanda_st = (int(xmin),int(ymin))
184
+ sand_end = (int(xmin),int(ymax))
185
+ sanda.append((sanda_st, sand_end))
186
+ line_midpoint.append(calculate_midpoint(sanda_st,sand_end))
187
+ #for calculation
188
+ width = distance((xmin,ymin), (xmin,ymax))
189
+ width_pixels.append(width)
190
+
191
+ return width_pixels, lines, sanda, line_midpoint
192
+
193
+ def pxl2meter(width_pixels, ratio):
194
+ real_width = []
195
+ for width in width_pixels:
196
+ real_width.append(round(width*ratio, 2))
197
+ return real_width
198
+
199
+ def width_as_char(real_width):
200
+ char_width = []
201
+ for width in real_width:
202
+ char_width.append(f"{width}m")
203
+ return char_width
204
+
205
+ def add_annotations_to_pdf(image, pdf_name, lines, sanda, char_width, line_midpoint):
206
+ image_width, image_height = image.size
207
+
208
+ # Create a new PDF document
209
+ pdf_document = fitz.open()
210
+
211
+ # Add a new page to the document with the same dimensions as the image
212
+ page = pdf_document.new_page(width=image_width, height=image_height)
213
 
214
+ # Insert the image into the PDF page
215
+ image_stream = io.BytesIO()
216
+ image.save(image_stream, format="PNG")
217
+ page.insert_image(page.rect, stream=image_stream.getvalue())
218
+
219
+
220
+ #Annotation for drawin lines as in the markups
221
+ for i in range(len(line_midpoint)):
222
+ x, y = line_midpoint[i]
223
+ text = char_width[i]
224
+ rect = fitz.Rect(x, y, x + 200, y + 50) # Adjust the width and height as needed
225
+ annot = page.add_freetext_annot(rect, text, fontsize=10, fontname="helv", text_color=(1,0,0))
226
+ annot.update()
227
+ #Annotation for drawin lines as in the markups
228
+ for i in range(len(lines)):
229
+ annot = page.add_line_annot(lines[i][0], lines[i][1])
230
+ annot = page.add_line_annot(sanda[i][0], lines[i][0])
231
+ annot = page.add_line_annot(sanda[i][1], lines[i][1])
232
+ annot.set_border(width=2, dashes=None) # Optional border styling
233
+ annot.set_colors(stroke=(1, 0, 0)) # Set the line color to red
234
+ annot.update()
235
+
236
+
237
+ output_pdf_path = pdf_name+"_annotated.pdf"
238
+ # Save the PDF with annotations
239
+
240
+ return pdf_document
241
+
242
+
243
+
244
+ '''def calculate_width(bbox):
245
  #if looking right or left, width < height
246
  bbox_width = bbox[2] - bbox[0]
247
  bbox_height = bbox[3] - bbox[1]
 
250
  else:
251
  door_width = bbox_height
252
  return door_width
253
+ '''
254
+ '''def width_annotations(bbox, ratio):
255
  lines = []
256
  width = []
257
 
 
272
  x = (x1+x1)/2
273
  y = (y1+y2)/2
274
  width.append(((x,y), door_width))
275
+ return lines, width'''
276
 
277
+ '''def create_width_annotations(width_info):
278
  annotations = []
279
  for i in range(len(width_info)):
280
  annotations.append(((width_info[i][0][0]),(width_info[i][0][1]),f"{width_info[i][1]} m"))
281
+ return annotations'''
282
 
283
+ '''def calculate_midpoint(top_left, bottom_right):
284
  x1, y1 = top_left
285
  x2, y2 = bottom_right
286
  # Calculate the midpoint
287
  xm = int((x1 + x2) / 2)
288
  ym = int((y1 + y2) / 2)
289
+ return (xm, ym)'''
290
 
291
+ '''def mid_points_bbox(bbox):
292
  midpoint = []
293
  for i in range(len(bbox)):
294
  x1 = int(bbox[i][0])
 
298
  top_left_corner = (x1, y1)
299
  bottom_right_corner = (x2, y2)
300
  midpoint.append(calculate_midpoint(top_left_corner, bottom_right_corner))
301
+ return midpoint'''
302
 
303
+ '''def create_annotations(door_kind, midpoints):
304
  door = door_kind
305
  annotations = []
306
  for i in range(len(midpoints)):
 
370
  return pdf_document
371
  # pdf_document.save(output_pdf_path)
372
  # pdf_document.close()
373
+ '''
374
  def main_run(pdf_fullpath, weights_path, pdf_name,pdfpath,ratio): ####pdf_fullpath here is the data and not the path
375
  img_pillow = convert2pillow(pdf_fullpath)
376
  #new_image = img_pillow.resize((2384, 1684))
377
 
378
  # Specify the number of classes (including the background)
379
+ num_classes = 10 # Ensure this matches the saved model's number of classes
380
 
381
  # Load the model with the specified number of classes
382
  model = get_model(num_classes)
 
397
  model.to(device)
398
 
399
  # START INFERENCE
400
+ #sbox, dbox = ev_model(img_pillow, model, device, 0.6)
401
 
402
  #Dataframe for Doors count
403
+ #doors_count = {'Type': ['Single Doors', 'Double Doors'], 'Quantity': [len(sbox), len(dbox)]}
404
+ #df_doors = pd.DataFrame(doors_count)
405
 
406
+ #single_midpoint = mid_points_bbox(sbox)
407
+ #double_midpoint = mid_points_bbox(dbox)
408
 
409
  #Kind Annotations
410
+ #single_annotations = create_annotations("single door", single_midpoint)
411
+ #double_annotations = create_annotations("double door", double_midpoint)
412
  #Lines Annotations
413
+ #line_single, width_signle = width_annotations(sbox, 1)
414
+ #line_double, width_double = width_annotations(dbox, 1)
415
  #Width Annotations
416
+ #width_single_ann = create_width_annotations(width_signle)
417
+ #width_double_ann = create_width_annotations(width_double)
418
 
419
  # add_annotations_to_pdf(new_image, pdf_name, single_annotations, double_annotations)
420
+
421
+
422
+ #NEW
423
+ doors_info = ev_model(img_pillow, model, device, 0.9)
424
+ width_pixels, lines, sanda, line_midpoint = get_door_info(doors_info)
425
+ real_width = pxl2meter(width_pixels, ratio)
426
+ char_width = width_as_char(real_width)
427
+
428
+ pdf_document = add_annotations_to_pdf(img_pillow, plan, lines, sanda, char_width, line_midpoint)
429
+
430
+ #pdf_document=add_annotations_to_pdf(img_pillow, pdf_name, single_annotations, double_annotations,width_single_ann,width_double_ann,line_single,line_double)
431
 
432
  page=pdf_document[0]
433
  pix = page.get_pixmap() # render page to an image
 
442
  for annot in page.annots():
443
  list1.loc[len(list1)] =annot.info
444
 
445
+
446
+ # modify this return
447
  return annotatedimg, pdf_document , spreadsheet_url, list1 , df_doors
448
 
449
  # model_path = '/content/drive/MyDrive/combined.pth'