SaliencyMapDemo / src /saliency.py
umyuu
flake8
8ccf878
raw
history blame
2.38 kB
# -*- coding: utf-8 -*-
"""SaliencyMapใ‚’่จˆ็ฎ—ใ™ใ‚‹"""
from typing import Any, Tuple, Literal
import numpy as np
import cv2
class SaliencyMap:
"""
SaliencyMap ้ก•่‘—ๆ€งใƒžใƒƒใƒ—ใ‚’่จˆ็ฎ—ใ™ใ‚‹ใ‚ฏใƒฉใ‚นใงใ™ใ€‚
Example:
from lib.saliency import SaliencyMap
saliency = SaliencyMap("SpectralResidual")
success, saliencyMap = saliency.compute(image)
"""
def __init__(
self,
algorithm: Literal["SpectralResidual", "FineGrained"] = "SpectralResidual",
):
self.algorithm = algorithm
# OpenCVใฎsaliencyใ‚’ไฝœๆˆใ—ใพใ™ใ€‚
if algorithm == "SpectralResidual":
self.saliency = cv2.saliency.StaticSaliencySpectralResidual_create()
else:
self.saliency = cv2.saliency.StaticSaliencyFineGrained_create()
def compute(self, image: np.ndarray) -> Tuple[bool, Any]:
"""
ๅ…ฅๅŠ›็”ปๅƒใ‹ใ‚‰้ก•่‘—ๆ€งใƒžใƒƒใƒ—ใ‚’ไฝœๆˆใ—ใพใ™ใ€‚
Parameters:
image: ๅ…ฅๅŠ›็”ปๅƒ
Returns:
bool:
true: SaliencyMap computed, false:NG
np.ndarray: ้ก•่‘—ๆ€งใƒžใƒƒใƒ—
"""
# ็”ปๅƒใฎ้ก•่‘—ๆ€งใ‚’่จˆ็ฎ—ใ—ใพใ™ใ€‚
return self.saliency.computeSaliency(image)
def convert_colormap(
image: np.ndarray,
saliency_map: np.ndarray,
colormap_name: Literal["jet", "hot", "turbo"] = "jet"
):
"""
้ก•่‘—ๆ€งใƒžใƒƒใƒ—ใ‚’ใ‚ซใƒฉใƒผใƒžใƒƒใƒ—ใซๅค‰ๆ›ๅพŒใซใ€ๅ…ฅๅŠ›็”ปๅƒใซ้‡ใญๅˆใ‚ใ›ใ—ใพใ™ใ€‚
Parameters:
image: ๅ…ฅๅŠ›็”ปๅƒ
saliency_map: ้ก•่‘—ๆ€งใƒžใƒƒใƒ—
colormap_name: ใ‚ซใƒฉใƒผใƒžใƒƒใƒ—ใฎ็จฎ้กž
Returns:
np.ndarray: ้‡ใญๅˆใ‚ใ›ใŸ็”ปๅƒ(RGBAๅฝขๅผ)
"""
maps = {"jet": cv2.COLORMAP_JET, "hot": cv2.COLORMAP_HOT, "turbo": cv2.COLORMAP_TURBO}
if colormap_name not in maps:
raise ValueError(colormap_name)
# ้ก•่‘—ๆ€งใƒžใƒƒใƒ—ใ‚’ใ‚ซใƒฉใƒผใƒžใƒƒใƒ—ใซๅค‰ๆ›
saliency_map = (saliency_map * 255).astype("uint8")
saliency_map = cv2.applyColorMap(saliency_map, maps[colormap_name])
#return saliencyMap
# ๅ…ฅๅŠ›็”ปๅƒใจใ‚ซใƒฉใƒผใƒžใƒƒใƒ—ใ‚’้‡ใญๅˆใ‚ใ›
overlay = cv2.addWeighted(image, 0.5, saliency_map, 0.5, 0)
#return overlay
return cv2.cvtColor(overlay, cv2.COLOR_BGR2RGBA)