Pavan2k4's picture
Update Utils/area.py
3c4d8fa verified
import cv2
import numpy as np
def pixel_to_sqft(pixel_area, resolution_cm=30):
area_cm2 = pixel_area * (resolution_cm ** 2)
area_m2 = area_cm2 / 10000.0
area_ft2 = area_m2 * 10.7639
return area_ft2
def process_and_overlay_image(original_image, mask_prediction, output_image_path = None, resolution_cm=30):
# Load original image
# Convert mask prediction to binary mask
mask = mask_prediction.astype(np.uint8) * 255
# Find contours in the mask
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# List to hold areas in square feet
areas_sqft = []
for contour in contours:
area_pixels = cv2.contourArea(contour)
area_sqft = pixel_to_sqft(area_pixels, resolution_cm)
areas_sqft.append(area_sqft)
# Draw contours on the original image
cv2.drawContours(original_image, [contour], -1, (0, 255, 0), int(0.5)) # Green color for contours
# Calculate and draw centroid
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
else:
cX, cY = 0, 0
cv2.putText(original_image, f'{area_sqft:.0f}', (cX, cY),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
# Save and display the image with contours
#cv2.imwrite(output_image_path, cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB))
# Display the image using matplotlib
#return original_image
return (cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB))