Spaces:
Sleeping
Sleeping
from unet.predict import predict_img,mask_to_image | |
import torch | |
from PIL import Image | |
import numpy as np | |
import cv2 | |
# μλλ unetμ΄κ³ dinov2 μ μ μ€ννλ λͺ¨λΈμ λλ€. | |
def segmentation(img): | |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
#device=torch.device("cuda") | |
net=torch.load("weights/unet.pth") | |
mask_values=[[0, 0, 0], [255, 255, 255]] | |
mask=predict_img(net,img,device,scale_factor=1,out_threshold=0.5) | |
result = mask_to_image(mask, mask_values) | |
result=np.array(result) | |
return result | |
# μ segmentation μ ν΅ν΄μ crop λ λΆλΆμ΄ μ΄λ―Έμ§λ΄μμ λͺνλ‘ μ°¨μ§νλμ§ κ³μ°ν©λλ€. | |
# μλ ν¨μλ dinov2, unetλͺ¨λμκ² μ μ©ν©λλ€ | |
# μλ μ½λλ νμμ ν½μ μ΄ μ°μμ μΌλ‘ μ΄μ΄μ Έμ λ§λ€μ΄μ§ λ©μ΄λ¦¬κ° μ 체μμ λͺνλ‘ μ°¨μ§νλμ§ κ³μ°ν©λλ€. | |
# μλ μ½λλ λ©μ΄λ¦¬(μ‘μ₯μΌλ‘ μΆμ ) λ€μ΄ 2κ° μ΄μμ΄μ΄λ μ μ©ν μ μμ΅λλ€. | |
def mask_percentage(mask_path): | |
image = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) | |
ret, threshold = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) | |
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
total_area = image.shape[0] * image.shape[1] | |
contours_list=contours | |
contour_areas = [cv2.contourArea(contour) for contour in contours] | |
percentages = [(area / total_area) * 100 for area in contour_areas] | |
percentage_list=[] | |
for i, percentage in enumerate(percentages): | |
percentage_list.append(percentage) | |
return contours_list,percentage_list | |