Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files217 unmodified lines2182192202212212222232242262252262272282312292302311 unmodified line2332342352392362372422382392405 unmodified lines2462472482492542502512522532542552602562572583 unmodified lines2622632642702652662672742682692709 unmodified lines2802812822902832842859 unmodified lines2952962973062982993003013023083033043056 unmodified lines31231331432131531631731831932032132832232333033132432532632732874 unmodified lines40340440541240640740840941041141241341413 unmodified lines42842943043243143243352 unmodified lines48648748849148949049149227 unmodified lines52052152252552352452517 unmodified lines54354454554954654754810 unmodified lines55956056156256356456856556656756857256957057157225 unmodified lines5985996006046016026032 unmodified lines60660760861360961061121 unmodified lines63363463564163663763828 unmodified lines66766866967667067167267368067467567667714 unmodified lines692693694701695696697698217 unmodified lines
def compute_foreshortening(plane_mask, depth_norm, px_per_ft, ref_depth): """Estimate perspective obliquity (sec theta) from horizontal depth gradient.""" ys, xs = np.where(plane_mask > 0) if len(ys) < 100 or px_per_ft <= 1e-3: return 1.0, 0.0
# Relative metric depth Z (in arbitrary units anchored to ref_depth = 1.0) d_vals = np.maximum(depth_norm[ys, xs].astype(np.float32), 25.0) z_rel = ref_depth / d_vals z_med = float(np.median(z_rel))
# Fit linear slope dZ / dx_px across the wall's horizontal span x_mean = float(np.mean(xs)) z_mean = float(np.mean(z_rel)) denom = float(np.sum((xs - x_mean) ** 2))1 unmodified line return 1.0, 0.0
dz_dx_px = abs(float(np.sum((xs - x_mean) * (z_rel - z_mean))) / denom) # Approximate camera focal length in pixels (~0.85 * image width for typical interiors) h, w = plane_mask.shape focal_px = 0.85 * float(max(h, w)) # tan(theta) = (dZ/dx_px) * (focal_px / Z_med) tan_theta = (dz_dx_px * focal_px) / max(z_med, 0.25) sec_theta = float(np.clip(np.sqrt(1.0 + tan_theta * tan_theta), 1.0, 2.25)) angle_deg = float(np.degrees(np.arccos(1.0 / sec_theta)))5 unmodified lines if len(ys) == 0 or px_per_ft <= 1e-3: return 0.0 d_vals = np.maximum(depth_norm[ys, xs].astype(np.float32), 25.0) # Allow up to 3.2x perspective scaling for deep back walls, floors, and ceilings rel_scale = np.clip(ref_depth / d_vals, 0.6, 1.8) rel_scale = np.clip(ref_depth / d_vals, 0.55, 3.2) ft_per_px = (1.0 / px_per_ft) * rel_scale return float(np.sum(ft_per_px * ft_per_px)) * float(foreshortening)
def estimate_gross_floor_mask(floor_mask, floor_furniture_mask, wall_mask): """Reconstruct occluded floor footprint below the wall-floor horizon.""" h, w = floor_mask.shape floor_ys = np.where(floor_mask > 0)[0] if len(floor_ys) == 0:3 unmodified lines valid_zone = np.zeros((h, w), np.uint8) valid_zone[horizon_y:, :] = 255
# Include floor + furniture resting on the floor below the wall-floor horizon combined = cv2.bitwise_or( floor_mask, cv2.bitwise_and(floor_furniture_mask, valid_zone) ) # Exclude upper wall pixels so the hull doesn't climb up walls combined = cv2.bitwise_and(combined, cv2.bitwise_not(wall_mask))
pts = cv2.findNonZero(combined)9 unmodified lines
def calibrate_scale(masks, door_mask, depth_norm, cal_mode, ref_dim_ft, h, w): """Calibrate pixels-per-foot and reference depth from Ceiling Height or Door Height.""" if cal_mode == "Door Height (ft)" and np.count_nonzero(door_mask) > 400: num_l, labels, stats, _ = cv2.connectedComponentsWithStats(door_mask) best_lbl = 09 unmodified lines px_per_ft = max(door_h_px / ref_dim_ft, 5.0) d_vals = depth_norm[labels == best_lbl] ref_depth = max(float(np.median(d_vals)), 30.0) if len(d_vals) > 0 else 128.0 return px_per_ft, ref_depth, f"Door Height ({ref_dim_ft:.1f} ft)" return px_per_ft, ref_depth, ref_dim_ft, f"Door Height ({ref_dim_ft:.1f} ft)"
# If Door Height was selected but no door exists in the image, default ceiling height to 10.0 ft effective_ceil_ft = 10.0 if cal_mode == "Door Height (ft)" else ref_dim_ft
# Default / fallback: Ceiling Height anchored to full-height wall columns wall_cols = np.where(np.any(masks["wall"] > 0, axis=0))[0] col_heights = [] full_col_depths = []6 unmodified lines full_col_depths.append(float(np.median(depth_norm[ys, x])))
median_wall_px = float(np.percentile(col_heights, 65)) if col_heights else h * 0.55 px_per_ft = max(median_wall_px / ref_dim_ft, 5.0) px_per_ft = max(median_wall_px / effective_ceil_ft, 5.0) if full_col_depths: ref_depth = max(float(np.median(full_col_depths)), 30.0) else: w_depths = depth_norm[masks["wall"] > 0] ref_depth = max(float(np.median(w_depths)), 30.0) if len(w_depths) > 0 else 128.0
note = f"Ceiling Height ({ref_dim_ft:.1f} ft)" note = f"Ceiling Height ({effective_ceil_ft:.1f} ft)" if cal_mode == "Door Height (ft)": note += " [no door detected, fallback]" return px_per_ft, ref_depth, note note += " [no door detected, defaulted to 10.0 ft]" return px_per_ft, ref_depth, effective_ceil_ft, note
def export_takeoff_files(payload, rows):74 unmodified lines "carpet", "ottoman", "armchair", "desk", "bench", ) display_keywords = ("television", "tv", "screen", "monitor", "painting", "picture") all_clutter_keywords = opening_keywords + floor_furn_keywords + display_keywords + ("cushion", "pillow", "curtain", "drape") all_clutter_keywords = ( opening_keywords + floor_furn_keywords + display_keywords + ("cushion", "pillow", "curtain", "drape") )
for cls_id in np.unique(pred_resized).tolist(): cid = int(cls_id)13 unmodified lines if any(ck in lbl for ck in all_clutter_keywords): clutter_mask = cv2.bitwise_or(clutter_mask, m)
# Suppress corners on furniture (9x9) and TV/display bezels (21x21) corner_block_mask = cv2.bitwise_or( cv2.dilate(clutter_mask, np.ones((9, 9), np.uint8)), cv2.dilate(display_mask, np.ones((21, 21), np.uint8)),52 unmodified lines edge_candidates, gray, junction_lines, min_len=min_l )
px_per_ft, ref_depth, cal_label = calibrate_scale( px_per_ft, ref_depth, used_ft, cal_label = calibrate_scale( masks, door_mask, depth_norm, cal_mode, ref_val, h, w )
27 unmodified lines for x1, y1, x2, y2 in clean_lines: cv2.line(overlay, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 255), 2)
# Per-wall foreshortened Net & Gross area calculation claimed_openings = np.zeros((h, w), np.uint8) plane_lines = [] wall_records = []17 unmodified lines plane["mask"], depth_norm, px_per_ft, ref_depth, foreshortening=sec_theta )
# Find openings/built-ins adjacent to or embedded inside this wall's envelope wall_zone = cv2.dilate(plane["mask"], np.ones((21, 21), np.uint8)) local_openings = cv2.bitwise_and(wall_zone, openings_builtins_mask) local_openings = cv2.bitwise_and(10 unmodified lines total_deduct_sqft += deduct_sqft
cx, cy = plane["centroid"] tx = max(8, cx - 65) tag = f"W{idx + 1}: {net_sqft:.0f} sf ({sec_theta:.2f}x)" cv2.putText( overlay, tag, (max(8, cx - 65), cy), overlay, tag, (tx + 2, cy + 2), cv2.FONT_HERSHEY_SIMPLEX, 0.52, (0, 0, 0), 3, cv2.LINE_AA ) cv2.putText( overlay, tag, (max(8, cx - 65), cy), overlay, tag, (tx, cy), cv2.FONT_HERSHEY_SIMPLEX, 0.52, (255, 255, 255), 1, cv2.LINE_AA )
25 unmodified lines
total_gross_wall_sqft = total_net_wall_sqft + total_deduct_sqft
# Floor (Visible vs. Gross Occlusion-Compensated) & Ceiling vis_floor_sqft = estimate_area_sqft(masks["floor"], depth_norm, px_per_ft, ref_depth) gross_floor_mask = estimate_gross_floor_mask( masks["floor"], floor_furniture_mask, masks["wall"]2 unmodified lines ceil_sqft = estimate_area_sqft(masks["ceiling"], depth_norm, px_per_ft, ref_depth) est_gross_floor_sqft = max(vis_floor_sqft, hull_floor_sqft, ceil_sqft * 0.95)
# Detect clean structural corners scored_corners = [] for i in range(len(clean_lines)): for j in range(i + 1, len(clean_lines)):21 unmodified lines cv2.circle(overlay, (px, py), 8, (255, 50, 80), -1) cv2.circle(overlay, (px, py), 10, (255, 255, 255), 2)
# Add summary rows to CSV & JSON csv_rows.extend([ { "Surface": "Total Walls",28 unmodified lines ])
payload = { "pipeline_version": "v10", "pipeline_version": "v11", "image_size_px": {"width": w, "height": h}, "calibration": { "anchor": cal_label, "reference_ft": round(ref_val, 2), "reference_ft": round(used_ft, 2), "px_per_ft": round(px_per_ft, 2), }, "summary": {14 unmodified lines
total_px = h * w report_lines = [ f"Pipeline v10 — Foreshortened Net/Gross Area & Takeoff ({cal_label})", f"Pipeline v11 — Foreshortened Net/Gross Area & Takeoff ({cal_label})", f"Walls ({np.count_nonzero(masks['wall']) / total_px * 100:.1f}%): Net Paintable ~{total_net_wall_sqft:.1f} sq.ft | Openings ~{total_deduct_sqft:.1f} sq.ft | Gross ~{total_gross_wall_sqft:.1f} sq.ft ({total_gross_wall_sqft * 0.0929:.1f} sq.m)", f"Floor ({np.count_nonzero(masks['floor']) / total_px * 100:.1f}%): Visible ~{vis_floor_sqft:.1f} sq.ft | Est. Gross Footprint ~{est_gross_floor_sqft:.1f} sq.ft ({est_gross_floor_sqft * 0.0929:.1f} sq.m)", f"Ceiling ({np.count_nonzero(masks['ceiling']) / total_px * 100:.1f}%): Est. ~{ceil_sqft:.1f} sq.ft ({ceil_sqft * 0.0929:.1f} sq.m)",app.py+23-29