File size: 2,035 Bytes
9b879f1
 
 
 
 
 
 
 
 
 
088dab0
 
9b879f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
from dino.predict import predict_img,mask_to_image
import torch
from PIL import Image
import numpy as np
import cv2

# 솑μž₯뢀뢄을 crop ν•˜κΈ° μœ„ν•œ μ½”λ“œ 
# dinov2 λͺ¨λΈμ„ segmentation λͺ¨λΈλ‘œ ν™œμš©ν•˜μ˜€κ³  이λ₯Ό train ν•˜μ—¬μ„œ pretrained weightλ₯Ό weight 폴더에 μ €μž₯ν•˜κ³  μ•„λž˜μ™€ 같이 loadν•©λ‹ˆλ‹€.

def segmentation(img):
    #device=torch.device("cuda")
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    net=torch.load("weights/dinov2_model.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 


# def calculate_white_area_percentage(mask):
#     total_pixels = mask.size
#     print(total_pixels)
    
#     white_pixels = np.sum(np.all(mask >100, axis=-1))
    
#     white_area_percentage = (white_pixels / total_pixels) * 100
    
#     return white_area_percentage*3

    
# μœ„ segmentation 을 ν†΅ν•΄μ„œ crop 된 뢀뢄이 μ΄λ―Έμ§€λ‚΄μ—μ„œ λͺ‡ν”„λ‘œ μ°¨μ§€ν•˜λŠ”μ§€ κ³„μ‚°ν•©λ‹ˆλ‹€. 
# μ•„λž˜ μ½”λ“œλŠ” ν•˜μ–€μƒ‰ 픽셀이 μ—°μ†μ μœΌλ‘œ μ΄μ–΄μ Έμ„œ λ§Œλ“€μ–΄μ§„ 덩어리가 μ „μ²΄μ—μ„œ λͺ‡ν”„λ‘œ μ°¨μ§€ν•˜λŠ”μ§€ κ³„μ‚°ν•©λ‹ˆλ‹€. 
# μ•„λž˜ μ½”λ“œλŠ” 덩어리(솑μž₯으둜 μΆ”μ •) 듀이 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