text stringlengths 1 93.6k |
|---|
def setup_cfg(args):
|
# load config from file and command-line arguments
|
cfg = get_cfg()
|
cfg.merge_from_file(args.config_file)
|
cfg.merge_from_list(args.opts)
|
# Set score_threshold for builtin models
|
cfg.MODEL.RETINANET.SCORE_THRESH_TEST = args.confidence_threshold
|
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.confidence_threshold
|
cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = args.confidence_threshold
|
cfg.freeze()
|
return cfg
|
def get_last_conv_name(net):
|
"""
|
获取网络的最后一个卷积层的名字
|
:param net:
|
:return:
|
"""
|
layer_name = None
|
for name, m in net.named_modules():
|
if isinstance(m, nn.Conv2d):
|
layer_name = name
|
return layer_name
|
class GuidedBackPropagation(object):
|
def __init__(self, net):
|
self.net = net
|
for (name, module) in self.net.named_modules():
|
if isinstance(module, nn.ReLU):
|
module.register_backward_hook(self.backward_hook)
|
self.net.eval()
|
@classmethod
|
def backward_hook(cls, module, grad_in, grad_out):
|
"""
|
:param module:
|
:param grad_in: tuple,长度为1
|
:param grad_out: tuple,长度为1
|
:return: tuple(new_grad_in,)
|
"""
|
return torch.clamp(grad_in[0], min=0.0),
|
def __call__(self, inputs, index=0):
|
"""
|
:param inputs: {"image": [C,H,W], "height": height, "width": width}
|
:param index: 第几个边框
|
:return:
|
"""
|
self.net.zero_grad()
|
output = self.net.inference([inputs])
|
score = output[0]['instances'].scores[index]
|
score.backward()
|
return inputs['image'].grad # [3,H,W]
|
def norm_image(image):
|
"""
|
标准化图像
|
:param image: [H,W,C]
|
:return:
|
"""
|
image = image.copy()
|
image -= np.max(np.min(image), 0)
|
image /= np.max(image)
|
image *= 255.
|
return np.uint8(image)
|
def gen_cam(image, mask):
|
"""
|
生成CAM图
|
:param image: [H,W,C],原始图像
|
:param mask: [H,W],范围0~1
|
:return: tuple(cam,heatmap)
|
"""
|
# mask转为heatmap
|
heatmap = cv2.applyColorMap(np.uint8(255 * mask), cv2.COLORMAP_JET)
|
heatmap = np.float32(heatmap) / 255
|
heatmap = heatmap[..., ::-1] # gbr to rgb
|
# 合并heatmap到原始图像
|
cam = heatmap + np.float32(image)/255
|
return norm_image(cam), heatmap
|
def gen_gb(grad):
|
"""
|
生guided back propagation 输入图像的梯度
|
:param grad: tensor,[3,H,W]
|
:return:
|
"""
|
# 标准化
|
grad = grad.data.numpy()
|
gb = np.transpose(grad, (1, 2, 0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.