File size: 7,551 Bytes
bc97962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710899
 
bc97962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import torch
import torchvision


from PIL import Image
import numpy as np

from skimage.morphology import erosion

from dependecies.segroot.model import SegRoot
from dependecies.segroot.dataloader import pad_pair_256, normalize
from torchvision.transforms import v2 as transforms


import onnxruntime as ort
import cv2 as cv

import os

MODELS_PATH = r"./models"

def pad_256(img_path):
    image = Image.open(img_path)
    W, H = image.size
    img, _ = pad_pair_256(image, image)
    NW, NH = img.size
    img = torchvision.transforms.ToTensor()(img)
    img = normalize(img)
    return img, (H, W, NH, NW)

def pad_256_np(np_img):
    #image = Image.open(img_path)
    image = Image.fromarray(np_img)
    W, H = image.size
    img, _ = pad_pair_256(image, image)
    NW, NH = img.size
    img = torchvision.transforms.ToTensor()(img)
    img = normalize(img)
    return img, (H, W, NH, NW)

def merge_images(files, path=""):
    
    is_array = False
    if type(files[0]) == np.ndarray:
        is_array = True
        

    final_img = []
    resize_factor = 0.4
    offset0 = 930
    offset1 = 305 
    for index, file in enumerate(files):

        if is_array:
            img = file
        else:
            img = cv.imread(file)
            img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        #img = cv.resize(img, (0,0), fx=resize_factor, fy=resize_factor)
        img = cv.rotate(img, cv.ROTATE_90_CLOCKWISE)
        
        if index == 0:
            img = img[0:img.shape[0]-offset0,0:img.shape[1]]
            final_img = img
        elif index == len(file)-1:
            final_img = cv.vconcat([final_img, img])
        else:
            #final_img = np.concatenate((final_img, img), axis=1)
            img = img[0:img.shape[0]-offset1,0:img.shape[1]]
            final_img = cv.vconcat([final_img, img])
        
    final_img = cv.resize(final_img, (0,0), fx=resize_factor, fy=resize_factor)  
     
    #cv.imwrite(path, final_img)
    print(final_img.shape)
    
    return final_img

class RootSegmentor():
    
    def __init__(self, model_type):
        
        
        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        
        self.model_type = model_type
        
        if model_type != "seg_model":        
            self.initialize()

        return
    
    def initialize(self):
        
        width = 8
        depth = 5

        weights_path = os.path.join(MODELS_PATH, r"best_segnet-(8,5)-0.6441.pt")
        
        if self.model_type == "segroot":
            #weights_path = os.path.join(r"D:\local_mydev\roots_finetuning\SegRoot0\weights\best_segnet-(8,5)-0.6441.pt"
            #weights_path = r"D:\local_mydev\SegRoot\weights\best_segnet-(8,5)-0.6441.pt"
            #weights_path = r"\\CATALOGUE.CGIARAD.ORG\AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\best_segnet-(8,5)-0.6441.pt"
            #weights_path = os.path.join(MODELS_PATH, r"AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\best_segnet-(8,5)-0.6441.pt")
            weights_path = os.path.join(MODELS_PATH, r"best_segnet-(8,5)-0.6441.pt")
        elif self.model_type == "segroot_finetuned":
            #weights_path = r"\\CATALOGUE.CGIARAD.ORG\AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\segroot-(8,5)_finetuned.pt"
            #weights_path = os.path.join(MODELS_PATH, r"AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\segroot-(8,5)_finetuned.pt")
            weights_path = os.path.join(MODELS_PATH, r"segroot-(8,5)_finetuned.pt")
        elif self.model_type == "segroot_finetuned_dec":
            #weights_path = r"\\CATALOGUE.CGIARAD.ORG\AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\segroot-(8,5)_finetuned_dec_full.pt"
            #weights_path = r"\\CATALOGUE.CGIARAD.ORG\AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\segroot-(8,5)_finetuned_clas.pt"
            #weights_path = os.path.join(MODELS_PATH, r"AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\segroot-(8,5)_finetuned_clas.pt")
            weights_path = os.path.join(MODELS_PATH, r"segroot-(8,5)_finetuned.pt")
            
        self.model = SegRoot(width, depth).to(self.device)

        if self.device.type == "cpu":
            print("load weights to cpu")
            #print(weights_path.as_posix())
            self.model.load_state_dict(torch.load(weights_path, map_location="cpu"))
        else:
            print("load weights to gpu")
            #print(weights_path.as_posix())
            self.model.load_state_dict(torch.load(weights_path))
            
        for p in self.model.parameters():
            p.requires_grad = False
            
        self.model.eval()
                
        return    
    
    def predict(self, img_path):
        
        if self.model_type == "seg_model":
            
            print(str(type(img_path)))
            
            if type(img_path) == np.ndarray:
                img = img_path  
            else:
                img = cv.imread(img_path)
                img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
            
            weights_path = r"\\CATALOGUE.CGIARAD.ORG\AcceleratedBreedingInitiative\4.Scripts\AndresRuiz\local_mydata_backup\model\roots\roots_model.onnx"
            weights_path = os.path.join(MODELS_PATH,"roots_model.onnx") 
            ort_sess = ort.InferenceSession(weights_path
                                ,providers=ort.get_available_providers()
                                )
            
            dim = img.shape
            
            transforms_list = []
            transforms_list.append(transforms.ToTensor())
            transforms_list.append(transforms.Resize((800,800)))
            #transforms_list.append(transforms.CenterCrop(800))
            #transforms_list.append(transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))

            apply_t =  transforms.Compose(transforms_list) 

            img = apply_t(img)

            outputs = ort_sess.run(None, {'input': [img.numpy()]})
            
            print(outputs)

            #np_res = outputs[0][0]

            output_image = outputs[0][:,:,1]
            final = cv.resize(output_image, (dim[0], dim[1]))
                
            return final
            
        else:

            thres = 0.9
            
            print(str(type(img_path)))
            
            if type(img_path) == np.ndarray:
                img, dims = pad_256_np(img_path)    
            else:
                img, dims = pad_256(img_path)
        
            H, W, NH, NW = dims
            
            img = img.to(self.device)
            
            img = img.unsqueeze(0)
            output = self.model(img)

            output = torch.squeeze(output)
            torch.cuda.empty_cache()

            prediction = output
            
            prediction[prediction >= thres] = 1.0
            prediction[prediction < thres] = 0.0
            
            if self.device.type == "cpu":
                prediction = prediction.detach().numpy()
            else:
                prediction = prediction.cpu().detach().numpy()
                
            prediction = erosion(prediction)
            # reverse padding
            prediction = prediction[
                (NH - H) // 2 : (NH - H) // 2 + H, (NW - W) // 2 : (NW - W) // 2 + W
            ]

            return prediction