Spaces:
Sleeping
Sleeping
# -*- 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) | |