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