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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import io
|
| 5 |
+
import requests
|
| 6 |
+
import json
|
| 7 |
+
import base64
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import numpy as np
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import mmengine
|
| 12 |
+
from mmengine import Config, get
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import os
|
| 16 |
+
import cv2
|
| 17 |
+
import yaml
|
| 18 |
+
import torch
|
| 19 |
+
from torch.utils.data import DataLoader
|
| 20 |
+
from tqdm import tqdm
|
| 21 |
+
import datasets
|
| 22 |
+
import models
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from torchvision import transforms
|
| 26 |
+
from mmcv.runner import load_checkpoint
|
| 27 |
+
import visual_utils
|
| 28 |
+
from PIL import Image
|
| 29 |
+
from models.utils_prompt import get_prompt_inp, pre_prompt, pre_scatter_prompt, get_prompt_inp_scatter
|
| 30 |
+
|
| 31 |
+
device = torch.device("cpu")
|
| 32 |
+
|
| 33 |
+
def batched_predict(model, inp, coord, bsize):
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
model.gen_feat(inp)
|
| 36 |
+
n = coord.shape[1]
|
| 37 |
+
ql = 0
|
| 38 |
+
preds = []
|
| 39 |
+
while ql < n:
|
| 40 |
+
qr = min(ql + bsize, n)
|
| 41 |
+
pred = model.query_rgb(coord[:, ql: qr, :])
|
| 42 |
+
preds.append(pred)
|
| 43 |
+
ql = qr
|
| 44 |
+
pred = torch.cat(preds, dim=1)
|
| 45 |
+
return pred, preds
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def tensor2PIL(tensor):
|
| 49 |
+
toPIL = transforms.ToPILImage()
|
| 50 |
+
return toPIL(tensor)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def Decoder1_optical_instance(image_input):
|
| 54 |
+
with open('configs/fine_tuning_one_decoder.yaml', 'r') as f:
|
| 55 |
+
config = yaml.load(f, Loader=yaml.FullLoader)
|
| 56 |
+
model = models.make(config['model']).cpu()
|
| 57 |
+
sam_checkpoint = torch.load("./save/model_epoch_last.pth", map_location='cpu')
|
| 58 |
+
model.load_state_dict(sam_checkpoint, strict=False)
|
| 59 |
+
model.eval()
|
| 60 |
+
|
| 61 |
+
# img = np.array(image_input).copy()
|
| 62 |
+
label2color = visual_utils.Label2Color(cmap=visual_utils.color_map('Unify_double'))
|
| 63 |
+
# image_input.save(f'./save/visual_fair1m/input_img.png', quality=5)
|
| 64 |
+
img = transforms.Resize([1024, 1024])(image_input)
|
| 65 |
+
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229,0.224,0.225])])
|
| 66 |
+
input_img = transform(img)
|
| 67 |
+
input_img = input_img.unsqueeze(0)
|
| 68 |
+
image_embedding = model.image_encoder(input_img) # torch.Size([1, 256, 64, 64])
|
| 69 |
+
sparse_embeddings, dense_embeddings, scatter_embeddings = model.prompt_encoder(
|
| 70 |
+
points=None,
|
| 71 |
+
boxes=None,
|
| 72 |
+
masks=None,
|
| 73 |
+
scatter=None)
|
| 74 |
+
# 目标类预测decoder
|
| 75 |
+
low_res_masks, iou_predictions = model.mask_decoder(
|
| 76 |
+
image_embeddings=image_embedding,
|
| 77 |
+
image_pe=model.prompt_encoder.get_dense_pe(),
|
| 78 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
| 79 |
+
dense_prompt_embeddings=dense_embeddings,
|
| 80 |
+
multimask_output=False
|
| 81 |
+
)
|
| 82 |
+
pred = model.postprocess_masks(low_res_masks, model.inp_size, model.inp_size)
|
| 83 |
+
_, prediction = pred.max(dim=1)
|
| 84 |
+
prediction_to_save = label2color(prediction.cpu().numpy().astype(np.uint8))[0]
|
| 85 |
+
|
| 86 |
+
return prediction_to_save
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def Decoder1_optical_terrain(image_input):
|
| 90 |
+
with open('configs/fine_tuning_one_decoder.yaml', 'r') as f:
|
| 91 |
+
config = yaml.load(f, Loader=yaml.FullLoader)
|
| 92 |
+
model = models.make(config['model']).cpu()
|
| 93 |
+
sam_checkpoint = torch.load("./save/model_epoch_last.pth", map_location='cpu')
|
| 94 |
+
model.load_state_dict(sam_checkpoint, strict=False)
|
| 95 |
+
model.eval()
|
| 96 |
+
|
| 97 |
+
denorm = visual_utils.Denormalize(mean=[0.485, 0.456, 0.406],std=[0.229,0.224,0.225])
|
| 98 |
+
label2color = visual_utils.Label2Color(cmap=visual_utils.color_map('Unify_Vai'))
|
| 99 |
+
# image_input.save(f'./save/visual_fair1m/input_img.png', quality=5)
|
| 100 |
+
img = transforms.Resize([1024, 1024])(image_input)
|
| 101 |
+
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229,0.224,0.225])])
|
| 102 |
+
input_img = transform(img)
|
| 103 |
+
input_img = torch.unsqueeze(input_img, dim=0)
|
| 104 |
+
# input_img = transforms.ToTensor()(img).unsqueeze(0)
|
| 105 |
+
image_embedding = model.image_encoder(input_img) # torch.Size([1, 256, 64, 64])
|
| 106 |
+
sparse_embeddings, dense_embeddings, scatter_embeddings = model.prompt_encoder(
|
| 107 |
+
points=None,
|
| 108 |
+
boxes=None,
|
| 109 |
+
masks=None,
|
| 110 |
+
scatter=None)
|
| 111 |
+
low_res_masks_instanse, iou_predictions = model.mask_decoder(
|
| 112 |
+
image_embeddings=image_embedding,
|
| 113 |
+
# image_embeddings=image_embedding.unsqueeze(0),
|
| 114 |
+
image_pe=model.prompt_encoder.get_dense_pe(),
|
| 115 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
| 116 |
+
dense_prompt_embeddings=dense_embeddings,
|
| 117 |
+
# multimask_output=multimask_output,
|
| 118 |
+
multimask_output=False
|
| 119 |
+
)
|
| 120 |
+
# 地物类预测decoder
|
| 121 |
+
low_res_masks, iou_predictions_2 = model.mask_decoder_diwu(
|
| 122 |
+
image_embeddings=image_embedding,
|
| 123 |
+
image_pe=model.prompt_encoder.get_dense_pe(),
|
| 124 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
| 125 |
+
dense_prompt_embeddings=dense_embeddings,
|
| 126 |
+
# multimask_output=False,
|
| 127 |
+
multimask_output=True,
|
| 128 |
+
) # B*C+1*H*W
|
| 129 |
+
|
| 130 |
+
pred_instance = model.postprocess_masks(low_res_masks_instanse, model.inp_size, model.inp_size)
|
| 131 |
+
pred = model.postprocess_masks(low_res_masks, model.inp_size, model.inp_size)
|
| 132 |
+
pred = torch.softmax(pred,dim=1)
|
| 133 |
+
pred_instance = torch.softmax(pred_instance,dim=1)
|
| 134 |
+
_, prediction = pred.max(dim=1)
|
| 135 |
+
prediction[prediction==12]=0 #把第二个decoder里得背景变成0
|
| 136 |
+
print(torch.unique(prediction))
|
| 137 |
+
_, prediction_instance = pred_instance.max(dim=1)
|
| 138 |
+
print(torch.unique(prediction_instance))
|
| 139 |
+
prediction_sum = prediction + prediction_instance #没有冲突的位置就会正常猜测
|
| 140 |
+
print(torch.unique(prediction_sum))
|
| 141 |
+
prediction_tmp = prediction_sum.clone()
|
| 142 |
+
prediction_tmp[prediction_tmp==1] = 255
|
| 143 |
+
prediction_tmp[prediction_tmp==2] = 255
|
| 144 |
+
prediction_tmp[prediction_tmp==5] = 255
|
| 145 |
+
prediction_tmp[prediction_tmp==6] = 255
|
| 146 |
+
prediction_tmp[prediction_tmp==14] = 255
|
| 147 |
+
# prediction_tmp[prediction_tmp==0] = 255 #同时是背景
|
| 148 |
+
# index = prediction_tmp != 255
|
| 149 |
+
pred[:, 0][prediction_tmp == 255]=100 #把已经决定的像素位置的背景预测概率设置为最大
|
| 150 |
+
pred_instance[:, 0][prediction_tmp == 255]=100#把已经决定的像素位置的背景预测概率设置为最大
|
| 151 |
+
buchong = torch.zeros([1,2,1024,1024])
|
| 152 |
+
pred = torch.cat((pred, buchong),dim=1)
|
| 153 |
+
# print(torch.unique(torch.argmax(pred,dim=1)))
|
| 154 |
+
# Decoder1_logits = torch.zeros([1,15,1024,1024]).cuda()
|
| 155 |
+
Decoder2_logits = torch.zeros([1,15,1024,1024])
|
| 156 |
+
Decoder2_logits[:,0,...] = pred[:,0,...]
|
| 157 |
+
Decoder2_logits[:,5,...] = pred_instance[:,5,...]
|
| 158 |
+
Decoder2_logits[:,14,...] = pred_instance[:,14,...]
|
| 159 |
+
Decoder2_logits[:,1,...] = pred[:,1,...]
|
| 160 |
+
Decoder2_logits[:,2,...] = pred[:,2,...]
|
| 161 |
+
Decoder2_logits[:,6,...] = pred[:,6,...]
|
| 162 |
+
# Decoder_logits = Decoder1_logits+Decoder2_logits
|
| 163 |
+
pred_chongtu = torch.argmax(Decoder2_logits, dim=1)
|
| 164 |
+
# pred_pred = torch.argmax(Decoder1_logits, dim=1)
|
| 165 |
+
pred_predinstance = torch.argmax(Decoder2_logits, dim=1)
|
| 166 |
+
print(torch.unique(pred_chongtu))
|
| 167 |
+
pred_chongtu[prediction_tmp == 255] = 0
|
| 168 |
+
prediction_sum[prediction_tmp!=255] = 0
|
| 169 |
+
prediction_final = (pred_chongtu + prediction_sum).cpu().numpy()
|
| 170 |
+
prediction_to_save = label2color(prediction_final)[0]
|
| 171 |
+
|
| 172 |
+
return prediction_to_save
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def Multi_box_prompts(input_prompt):
|
| 176 |
+
with open('configs/fine_tuning_one_decoder.yaml', 'r') as f:
|
| 177 |
+
config = yaml.load(f, Loader=yaml.FullLoader)
|
| 178 |
+
model = models.make(config['model']).cpu()
|
| 179 |
+
sam_checkpoint = torch.load("./save/model_epoch_last.pth", map_location='cpu')
|
| 180 |
+
model.load_state_dict(sam_checkpoint, strict=False)
|
| 181 |
+
model.eval()
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
label2color = visual_utils.Label2Color(cmap=visual_utils.color_map('Unify_double'))
|
| 185 |
+
# image_input.save(f'./save/visual_fair1m/input_img.png', quality=5)
|
| 186 |
+
img = transforms.Resize([1024, 1024])(input_prompt["image"])
|
| 187 |
+
input_img = transforms.ToTensor()(img).unsqueeze(0)
|
| 188 |
+
image_embedding = model.image_encoder(input_img) # torch.Size([1, 256, 64, 64])
|
| 189 |
+
sparse_embeddings, dense_embeddings, scatter_embeddings = model.prompt_encoder(
|
| 190 |
+
points=None,
|
| 191 |
+
boxes=None,
|
| 192 |
+
masks=None,
|
| 193 |
+
scatter=None)
|
| 194 |
+
# 目标类预测decoder
|
| 195 |
+
low_res_masks, iou_predictions = model.mask_decoder(
|
| 196 |
+
image_embeddings=image_embedding,
|
| 197 |
+
image_pe=model.prompt_encoder.get_dense_pe(),
|
| 198 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
| 199 |
+
dense_prompt_embeddings=dense_embeddings,
|
| 200 |
+
multimask_output=False
|
| 201 |
+
)
|
| 202 |
+
pred = model.postprocess_masks(low_res_masks, model.inp_size, model.inp_size)
|
| 203 |
+
_, prediction = pred.max(dim=1)
|
| 204 |
+
prediction_to_save = label2color(prediction.cpu().numpy().astype(np.uint8))[0]
|
| 205 |
+
|
| 206 |
+
def find_instance(image_map):
|
| 207 |
+
BACKGROUND = 0
|
| 208 |
+
steps = [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]]
|
| 209 |
+
instances = []
|
| 210 |
+
|
| 211 |
+
def bfs(x, y, category_id):
|
| 212 |
+
nonlocal image_map, steps
|
| 213 |
+
instance = {(x, y)}
|
| 214 |
+
q = [(x, y)]
|
| 215 |
+
image_map[x, y] = BACKGROUND
|
| 216 |
+
while len(q) > 0:
|
| 217 |
+
x, y = q.pop(0)
|
| 218 |
+
# print(x, y, image_map[x][y])
|
| 219 |
+
for step in steps:
|
| 220 |
+
xx = step[0] + x
|
| 221 |
+
yy = step[1] + y
|
| 222 |
+
if 0 <= xx < len(image_map) and 0 <= yy < len(image_map[0]) \
|
| 223 |
+
and image_map[xx][yy] == category_id: # and (xx, yy) not in q:
|
| 224 |
+
q.append((xx, yy))
|
| 225 |
+
instance.add((xx, yy))
|
| 226 |
+
image_map[xx, yy] = BACKGROUND
|
| 227 |
+
return instance
|
| 228 |
+
image_map = image_map[:]
|
| 229 |
+
for i in range(len(image_map)):
|
| 230 |
+
for j in range(len(image_map[i])):
|
| 231 |
+
category_id = image_map[i][j]
|
| 232 |
+
if category_id == BACKGROUND:
|
| 233 |
+
continue
|
| 234 |
+
instances.append(bfs(i, j, category_id))
|
| 235 |
+
return instances
|
| 236 |
+
|
| 237 |
+
prompts = find_instance(np.uint8(np.array(input_prompt["mask"]).sum(-1) != 0))
|
| 238 |
+
img_mask = np.array(img).copy()
|
| 239 |
+
|
| 240 |
+
def get_box(prompt):
|
| 241 |
+
xs = []
|
| 242 |
+
ys = []
|
| 243 |
+
for x, y in prompt:
|
| 244 |
+
xs.append(x)
|
| 245 |
+
ys.append(y)
|
| 246 |
+
return [[min(xs), min(ys)], [max(xs), max(ys)]]
|
| 247 |
+
|
| 248 |
+
def in_box(point, box):
|
| 249 |
+
left_up, right_down = box
|
| 250 |
+
x, y = point
|
| 251 |
+
return x >= left_up[0] and x <= right_down[0] and y >= left_up[1] and y <= right_down[1]
|
| 252 |
+
|
| 253 |
+
def draw_box(box_outer, img, radius=4):
|
| 254 |
+
radius -= 1
|
| 255 |
+
left_up_outer, right_down_outer = box_outer
|
| 256 |
+
box_inner = [list(np.array(left_up_outer) + radius),
|
| 257 |
+
list(np.array(right_down_outer) - radius)]
|
| 258 |
+
for x in range(len(img)):
|
| 259 |
+
for y in range(len(img[x])):
|
| 260 |
+
if in_box([x, y], box_outer):
|
| 261 |
+
img_mask[x, y] = (1, 1, 1)
|
| 262 |
+
if in_box([x, y], box_outer) and (not in_box([x, y], box_inner)):
|
| 263 |
+
img[x, y] = (255, 0, 0)
|
| 264 |
+
return img
|
| 265 |
+
|
| 266 |
+
for prompt in prompts:
|
| 267 |
+
box = get_box(prompt)
|
| 268 |
+
output = draw_box(box, prediction_to_save) * (img_mask==1)
|
| 269 |
+
|
| 270 |
+
return output
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def Decoder2_SAR(SAR_image, SAR_prompt):
|
| 275 |
+
with open('configs/multi_mo_multi_task_sar_prompt.yaml', 'r') as f:
|
| 276 |
+
config = yaml.load(f, Loader=yaml.FullLoader)
|
| 277 |
+
model = models.make(config['model']).cpu()
|
| 278 |
+
sam_checkpoint = torch.load("./save/SAR/model_epoch_last.pth", map_location='cpu')
|
| 279 |
+
model.load_state_dict(sam_checkpoint, strict=True)
|
| 280 |
+
model.eval()
|
| 281 |
+
|
| 282 |
+
denorm = visual_utils.Denormalize(mean=[0.485, 0.456, 0.406],std=[0.229,0.224,0.225])
|
| 283 |
+
label2color = visual_utils.Label2Color(cmap=visual_utils.color_map('Unify_YIJISAR'))
|
| 284 |
+
|
| 285 |
+
img = transforms.Resize([1024, 1024])(SAR_image)
|
| 286 |
+
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229,0.224,0.225])])
|
| 287 |
+
input_img = transform(img)
|
| 288 |
+
input_img = torch.unsqueeze(input_img, dim=0)
|
| 289 |
+
# input_img = transforms.ToTensor()(img).unsqueeze(0)
|
| 290 |
+
# input_img = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229,0.224,0.225])
|
| 291 |
+
filp_flag = torch.Tensor([False])
|
| 292 |
+
image_embedding = model.image_encoder(input_img)
|
| 293 |
+
|
| 294 |
+
# scattter_prompt = cv2.imread(scatter_file_, cv2.IMREAD_UNCHANGED)
|
| 295 |
+
# scattter_prompt = get_prompt_inp_scatter(name[0].replace('gt', 'JIHUAFENJIE'))
|
| 296 |
+
SAR_prompt = cv2.imread(SAR_prompt, cv2.IMREAD_UNCHANGED)
|
| 297 |
+
scatter_torch = pre_scatter_prompt(SAR_prompt, filp_flag, device=input_img.device)
|
| 298 |
+
scatter_torch = scatter_torch.unsqueeze(0)
|
| 299 |
+
scatter_torch = torch.nn.functional.interpolate(scatter_torch, size=(256, 256))
|
| 300 |
+
sparse_embeddings, dense_embeddings, scatter_embeddings = model.prompt_encoder(
|
| 301 |
+
points=None,
|
| 302 |
+
boxes=None,
|
| 303 |
+
masks=None,
|
| 304 |
+
scatter=scatter_torch)
|
| 305 |
+
# 地物类预测decoder
|
| 306 |
+
low_res_masks, iou_predictions_2 = model.mask_decoder_diwu(
|
| 307 |
+
image_embeddings=image_embedding,
|
| 308 |
+
image_pe=model.prompt_encoder.get_dense_pe(),
|
| 309 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
| 310 |
+
dense_prompt_embeddings=dense_embeddings,
|
| 311 |
+
# multimask_output=False,
|
| 312 |
+
multimask_output=True,
|
| 313 |
+
) # B*C+1*H*W
|
| 314 |
+
pred = model.postprocess_masks(low_res_masks, model.inp_size, model.inp_size)
|
| 315 |
+
_, prediction = pred.max(dim=1)
|
| 316 |
+
prediction = prediction.cpu().numpy()
|
| 317 |
+
prediction_to_save = label2color(prediction)[0]
|
| 318 |
+
|
| 319 |
+
return prediction_to_save
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
examples1_instance = [
|
| 323 |
+
['./images/optical/isaid/_P0007_1065_319_image.png'],
|
| 324 |
+
['./images/optical/isaid/_P0466_1068_420_image.png'],
|
| 325 |
+
['./images/optical/isaid/_P0897_146_34_image.png'],
|
| 326 |
+
['./images/optical/isaid/_P1397_844_904_image.png'],
|
| 327 |
+
['./images/optical/isaid/_P2645_883_965_image.png'],
|
| 328 |
+
['./images/optical/isaid/_P1398_1290_630_image.png']
|
| 329 |
+
]
|
| 330 |
+
|
| 331 |
+
examples1_terrain = [
|
| 332 |
+
['./images/optical/vaihingen/top_mosaic_09cm_area2_105_image.png'],
|
| 333 |
+
['./images/optical/vaihingen/top_mosaic_09cm_area4_227_image.png'],
|
| 334 |
+
['./images/optical/vaihingen/top_mosaic_09cm_area20_142_image.png'],
|
| 335 |
+
['./images/optical/vaihingen/top_mosaic_09cm_area24_128_image.png'],
|
| 336 |
+
['./images/optical/vaihingen/top_mosaic_09cm_area27_34_image.png']
|
| 337 |
+
]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
examples1_multi_box = [
|
| 341 |
+
['./images/optical/isaid/_P0007_1065_319_image.png'],
|
| 342 |
+
['./images/optical/isaid/_P0466_1068_420_image.png'],
|
| 343 |
+
['./images/optical/isaid/_P0897_146_34_image.png'],
|
| 344 |
+
['./images/optical/isaid/_P1397_844_904_image.png'],
|
| 345 |
+
['./images/optical/isaid/_P2645_883_965_image.png'],
|
| 346 |
+
['./images/optical/isaid/_P1398_1290_630_image.png']
|
| 347 |
+
]
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
examples2 = [
|
| 351 |
+
['./images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_4_image.png', './images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_4.png'],
|
| 352 |
+
['./images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_15_image.png', './images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_15.png'],
|
| 353 |
+
['./images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_24_image.png', './images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_24.png'],
|
| 354 |
+
['./images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_41_image.png', './images/sar/YIJISARGF3_MYN_QPSI_001269_E113.2_N23.0_20161105_L1A_L10002009158_ampl_41.png'],
|
| 355 |
+
['./images/sar/YIJISARGF3_MYN_QPSI_999996_E121.2_N30.3_20160815_L1A_L10002015572_ampl_150_image.png', './images/sar/YIJISARGF3_MYN_QPSI_999996_E121.2_N30.3_20160815_L1A_L10002015572_ampl_150.png']
|
| 356 |
+
]
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
# RingMo-SAM designs two new promptable forms based on the characteristics of multimodal remote sensing images:
|
| 361 |
+
# multi-boxes prompt and SAR polarization scatter prompt.
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
title = "RingMo-SAM:A Foundation Model for Segment Anything in Multimodal Remote Sensing Images<br> \
|
| 365 |
+
<div align='center'> \
|
| 366 |
+
<h2><a href='https://ieeexplore.ieee.org/document/10315957' target='_blank' rel='noopener'>[paper]</a> \
|
| 367 |
+
<br> \
|
| 368 |
+
<image src='file/RingMo-SAM.gif' width='720px' /> \
|
| 369 |
+
<h2>RingMo-SAM can not only segment anything in optical and SAR remote sensing data, but also identify object categories.<h2> \
|
| 370 |
+
</div> \
|
| 371 |
+
"
|
| 372 |
+
|
| 373 |
+
# <a href='https://github.com/AICyberTeam' target='_blank' rel='noopener'>[code]</a></h2> \
|
| 374 |
+
# with gr.Blocks() as demo:
|
| 375 |
+
# image_input = gr.Image(type='pil', label='Input Img')
|
| 376 |
+
# image_output = gr.Image(label='Segment Result', type='numpy')
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
Decoder_optical_instance_io = gr.Interface(fn=Decoder1_optical_instance,
|
| 380 |
+
inputs=[gr.Image(type='pil', label='optical_instance_img(光学图像)')],
|
| 381 |
+
outputs=[gr.Image(label='segment_result', type='numpy')],
|
| 382 |
+
# title=title,
|
| 383 |
+
description="<p> \
|
| 384 |
+
Instance_Decoder:<br>\
|
| 385 |
+
Instance-type objects (such as vehicle, aircraft, ship, etc.) have a smaller proportion. <br>\
|
| 386 |
+
Our decoder can decouple the SAM's mask decoder into instance category decoder and terrain category decoder to ensure that the model fits adequately to both types of data. <br>\
|
| 387 |
+
Choose an example below, or, upload optical instance images to be tested. <br>\
|
| 388 |
+
Examples below were never trained and are randomly selected for testing in the wild. <br>\
|
| 389 |
+
</p>",
|
| 390 |
+
allow_flagging='auto',
|
| 391 |
+
examples=examples1_instance,
|
| 392 |
+
cache_examples=False,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
Decoder_optical_terrain_io = gr.Interface(fn=Decoder1_optical_terrain,
|
| 397 |
+
inputs=[gr.Image(type='pil', label='optical_terrain_img(光学图像)')],
|
| 398 |
+
# inputs=[gr.Image(type='pil', label='optical_img(光学图像)'), gr.Image(type='pil', label='SAR_img(SAR图像)'), gr.Image(type='pil', label='SAR_prompt(偏振散射提示)')],
|
| 399 |
+
outputs=[gr.Image(label='segment_result', type='numpy')],
|
| 400 |
+
# title=title,
|
| 401 |
+
description="<p> \
|
| 402 |
+
Terrain_Decoder:<br>\
|
| 403 |
+
Terrain-type objects (such as vegetation, land, river, etc.) have a larger proportion. <br>\
|
| 404 |
+
Our decoder can decouple the SAM's mask decoder into instance category decoder and terrain category decoder to ensure that the model fits adequately to both types of data. <br>\
|
| 405 |
+
Choose an example below, or, upload optical terrain images to be tested. <br>\
|
| 406 |
+
Examples below were never trained and are randomly selected for testing in the wild. <br>\
|
| 407 |
+
</p>",
|
| 408 |
+
allow_flagging='auto',
|
| 409 |
+
examples=examples1_terrain,
|
| 410 |
+
cache_examples=False,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
Decoder_multi_box_prompts_io = gr.Interface(fn=Multi_box_prompts,
|
| 416 |
+
inputs=[gr.ImageMask(brush_radius=4, type='pil', label='input_img(图像)')],
|
| 417 |
+
outputs=[gr.Image(label='segment_result', type='numpy')],
|
| 418 |
+
# title=title,
|
| 419 |
+
description="<p> \
|
| 420 |
+
Multi-box Prompts:<br>\
|
| 421 |
+
Multiple boxes are sequentially encoded as concated sparse high-dimensional feature embedding, \
|
| 422 |
+
the corresponding multiple high-dimensional features are concated together into a high-dimensional feature vector as part of the sparse embedding. <br>\
|
| 423 |
+
Choose an example below, or, upload images to be tested, and then draw multi-boxes. <br>\
|
| 424 |
+
Examples below were never trained and are randomly selected for testing in the wild. <br>\
|
| 425 |
+
</p>",
|
| 426 |
+
allow_flagging='auto',
|
| 427 |
+
examples=examples1_multi_box,
|
| 428 |
+
cache_examples=False,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
Decoder_SAR_io = gr.Interface(fn=Decoder2_SAR,
|
| 434 |
+
inputs=[gr.Image(type='pil', label='SAR_img(SAR图像)'), gr.Image(type='filepath', label='SAR_prompt(偏振散射提示)')],
|
| 435 |
+
outputs=[gr.Image(label='segment_result', type='numpy')],
|
| 436 |
+
description="<p> \
|
| 437 |
+
SAR Polarization Scatter Prompts:<br>\
|
| 438 |
+
Different terrain categories usually exhibit different scattering properties. \
|
| 439 |
+
Therefore, we code network for coded mapping of these SAR polarization scatter prompts to the corresponding SAR images, \
|
| 440 |
+
which improves the segmentation results of SAR images. <br>\
|
| 441 |
+
Choose an example below, or, upload SAR images and the corresponding polarization scatter prompts to be tested. <br>\
|
| 442 |
+
Examples below were never trained and are randomly selected for testing in the wild. <br>\
|
| 443 |
+
</p>",
|
| 444 |
+
allow_flagging='auto',
|
| 445 |
+
examples=examples2,
|
| 446 |
+
cache_examples=False,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# Decoder1_io.launch(server_name="0.0.0.0", server_port=34311)
|
| 451 |
+
# Decoder1_io.launch(enable_queue=False)
|
| 452 |
+
# demo = gr.TabbedInterface([Decoder1_io, Decoder2_io], ['Instance_Decoder', 'Terrain_Decoder'], title=title)
|
| 453 |
+
demo = gr.TabbedInterface([Decoder_optical_instance_io, Decoder_optical_terrain_io, Decoder_multi_box_prompts_io, Decoder_SAR_io], ['optical_instance_img(光学图像)', 'optical_terrain_img(光学图像)', 'multi_box_prompts(多框提示)', 'SAR_img(偏振散射提示)'], title=title).launch()
|
| 454 |
+
# -
|