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