Spaces:
Sleeping
Sleeping
File size: 1,662 Bytes
8804c8f 4cfe9f7 8804c8f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
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
|