├── pyimgsaliency ├── bird.jpg ├── __init__.py ├── demo.py ├── binarise.py ├── evaluate.py ├── saliency_mbd.py └── saliency.py ├── setup.py ├── .gitignore ├── README.md └── LICENSE /pyimgsaliency/bird.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yhenon/pyimgsaliency/HEAD/pyimgsaliency/bird.jpg -------------------------------------------------------------------------------- /pyimgsaliency/__init__.py: -------------------------------------------------------------------------------- 1 | from .saliency import * 2 | from .binarise import * 3 | from .saliency_mbd import * 4 | from .evaluate import * 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup(name='pyimgsaliency', 4 | version='0.1', 5 | description='A package for calculating image saliency', 6 | url='https://github.com/yhenon/pyimgsaliency', 7 | author='Yann Henon', 8 | author_email='none', 9 | license='Apache', 10 | install_requires=['sklearn', 'opencv-python', 'networkx', 'numpy', 'scipy', 'scikit-image'], 11 | packages=['pyimgsaliency'], 12 | zip_safe=False) 13 | -------------------------------------------------------------------------------- /pyimgsaliency/demo.py: -------------------------------------------------------------------------------- 1 | import pyimgsaliency as psal 2 | import cv2 3 | 4 | # path to the image 5 | filename = 'bird.jpg' 6 | 7 | # get the saliency maps using the 3 implemented methods 8 | rbd = psal.get_saliency_rbd(filename).astype('uint8') 9 | 10 | ft = psal.get_saliency_ft(filename).astype('uint8') 11 | 12 | mbd = psal.get_saliency_mbd(filename).astype('uint8') 13 | 14 | # often, it is desirable to have a binary saliency map 15 | binary_sal = psal.binarise_saliency_map(mbd,method='adaptive') 16 | 17 | img = cv2.imread(filename) 18 | 19 | cv2.imshow('img',img) 20 | cv2.imshow('rbd',rbd) 21 | cv2.imshow('ft',ft) 22 | cv2.imshow('mbd',mbd) 23 | 24 | #openCV cannot display numpy type 0, so convert to uint8 and scale 25 | cv2.imshow('binary',255 * binary_sal.astype('uint8')) 26 | 27 | 28 | cv2.waitKey(0) 29 | -------------------------------------------------------------------------------- /pyimgsaliency/binarise.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def binarise_saliency_map(saliency_map,method='adaptive',threshold=0.5): 4 | 5 | # check if input is a numpy array 6 | if type(saliency_map).__module__ != np.__name__: 7 | print('Expected numpy array') 8 | return None 9 | 10 | #check if input is 2D 11 | if len(saliency_map.shape) != 2: 12 | print('Saliency map must be 2D') 13 | return None 14 | 15 | if method == 'fixed': 16 | return (saliency_map > threshold) 17 | 18 | elif method == 'adaptive': 19 | adaptive_threshold = 2.0 * saliency_map.mean() 20 | return (saliency_map > adaptive_threshold) 21 | 22 | elif method == 'clustering': 23 | print('Not yet implemented') 24 | return None 25 | 26 | else: 27 | print("Method must be one of fixed, adaptive or clustering") 28 | return None 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask instance folder 57 | instance/ 58 | 59 | # Sphinx documentation 60 | docs/_build/ 61 | 62 | # PyBuilder 63 | target/ 64 | 65 | # IPython Notebook 66 | .ipynb_checkpoints 67 | 68 | # pyenv 69 | .python-version 70 | 71 | # dotenv 72 | .env 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyimgsaliency 2 | A python toolbox for image saliency calculation. 3 | 4 | 5 | The following algorithms are currently implemented for calculating saliency maps: 6 | - Jianming Zhang, Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price and Radomír Měch. "Minimum Barrier Salient Object Detection at 80 FPS." 7 | - Saliency Optimization from Robust Background Detection, Wangjiang Zhu, Shuang Liang, Yichen Wei and Jian Sun, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2014 8 | - R. Achanta, S. Hemami, F. Estrada and S. Süsstrunk, Frequency-tuned Salient Region Detection, IEEE International Conference on Computer Vision and Pattern Recognition (CVPR 2009), pp. 1597 - 1604, 2009 9 | 10 | An example of the use of this package can be seen at demo.py 11 | 12 | Original image: 13 | 14 | ![bird](http://imgur.com/kVLfhwy.png "Original image") 15 | 16 | Saliency detection with minimum barrier detection: 17 | 18 | ![bird](http://imgur.com/5Zu7T5V.png "mbd") 19 | 20 | Saliency detection with robust background detection: 21 | 22 | ![bird](http://imgur.com/SgywutJ.png "rbd") 23 | 24 | Saliency detection with frequency-tuned method: 25 | 26 | ![bird](http://imgur.com/t8NeAVi.png "ft") 27 | 28 | 29 | License 30 | Provided under the Apache 2.0 License. Note that there might be additional restrictions on some algorithms. In particular, the authors of "Minimum Barrier Salient Object Detection at 80 FPS" note that their algorithm is patent pending and may not be used in commercial applications. 31 | -------------------------------------------------------------------------------- /pyimgsaliency/evaluate.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pdb 3 | import pyimgsaliency 4 | import cv2 5 | import pdb 6 | import numpy as np 7 | import sklearn.metrics 8 | from matplotlib import pyplot as plt 9 | def evaluate(img_dir,gt_dir,methods): 10 | 11 | valid_extensions = ['.jpg','.png'] 12 | 13 | results_precision = {} 14 | results_recall = {} 15 | for filename in os.listdir(img_dir): 16 | if filename.endswith(".jpg") or filename.endswith(".png"): 17 | basename = os.path.splitext(filename)[0] 18 | gt_image_path = None 19 | if os.path.isfile(gt_dir + '/' + basename + '.png'): 20 | gt_image_path = gt_dir + '/' + basename + '.png' 21 | elif os.path.isfile(gt_dir + '/' + basename + '.jpg'): 22 | gt_image_path = gt_dir + '/' + basename + '.jpg' 23 | else: 24 | print('No match in gt directory for file' + str(filename) + ', skipping.') 25 | continue 26 | print(img_dir + '/' + filename) 27 | sal_image = pyimgsaliency.get_saliency_mbd(img_dir + '/' + filename).astype('uint8') 28 | gt_image = cv2.imread(gt_image_path,cv2.CV_LOAD_IMAGE_GRAYSCALE) 29 | cv2.imshow('sal',sal_image) 30 | cv2.imshow('img',gt_image) 31 | cv2.waitKey(0) 32 | if gt_image.shape != sal_image.shape: 33 | print('Size of image and GT image does not match, skipping') 34 | continue 35 | #precision, recall, thresholds = sklearn.metrics.precision_recall(y_true,y_scores) 36 | ''' 37 | precisions = {} 38 | recalls = {} 39 | 40 | num_pixels = sal_image.shape[0] * sal_image.shape[1] 41 | 42 | p = np.count_nonzero(gt_image) 43 | n = num_pixels - p 44 | 45 | for v in xrange(0,255): 46 | culled = np.copy(sal_image) 47 | culled[culled < v] = 0 48 | if np.count_nonzero(culled) == 0: 49 | recall = 1 50 | sensitivity = 0 51 | else: 52 | tp = np.count_nonzero(culled & gt_image) 53 | recall = float(tp)/p 54 | precision = float(tp) / np.count_nonzero(culled) 55 | 56 | precisions[v] = precision 57 | recalls[v] = recall 58 | 59 | results_precision[filename] = precisions 60 | results_recall[filename] = recalls 61 | 62 | x = [] 63 | y = [] 64 | for x1 in precisions: 65 | #print x1 66 | x.append(precisions[x1]) 67 | y.append(recalls[x1]) 68 | plt.plot(x,y) 69 | plt.show() 70 | ''' 71 | #pdb.set_trace() 72 | return (results_precision,results_recall) 73 | -------------------------------------------------------------------------------- /pyimgsaliency/saliency_mbd.py: -------------------------------------------------------------------------------- 1 | import math 2 | import sys 3 | import operator 4 | import networkx as nx 5 | #import matplotlib.pyplot as plt 6 | import numpy as np 7 | import scipy.spatial.distance 8 | import scipy.signal 9 | import skimage 10 | import skimage.io 11 | from skimage.segmentation import slic 12 | from skimage.util import img_as_float 13 | from scipy.optimize import minimize 14 | #import pdb 15 | 16 | def raster_scan(img,L,U,D): 17 | n_rows = len(img) 18 | n_cols = len(img[0]) 19 | 20 | for x in xrange(1,n_rows - 1): 21 | for y in xrange(1,n_cols - 1): 22 | ix = img[x][y] 23 | d = D[x][y] 24 | 25 | u1 = U[x-1][y] 26 | l1 = L[x-1][y] 27 | 28 | u2 = U[x][y-1] 29 | l2 = L[x][y-1] 30 | 31 | b1 = max(u1,ix) - min(l1,ix) 32 | b2 = max(u2,ix) - min(l2,ix) 33 | 34 | if d <= b1 and d <= b2: 35 | continue 36 | elif b1 < d and b1 <= b2: 37 | D[x][y] = b1 38 | U[x][y] = max(u1,ix) 39 | L[x][y] = min(l1,ix) 40 | else: 41 | D[x][y] = b2 42 | U[x][y] = max(u2,ix) 43 | L[x][y] = min(l2,ix) 44 | 45 | return True 46 | 47 | def raster_scan_inv(img,L,U,D): 48 | n_rows = len(img) 49 | n_cols = len(img[0]) 50 | 51 | for x in xrange(n_rows - 2,1,-1): 52 | for y in xrange(n_cols - 2,1,-1): 53 | 54 | ix = img[x][y] 55 | d = D[x][y] 56 | 57 | u1 = U[x+1][y] 58 | l1 = L[x+1][y] 59 | 60 | u2 = U[x][y+1] 61 | l2 = L[x][y+1] 62 | 63 | b1 = max(u1,ix) - min(l1,ix) 64 | b2 = max(u2,ix) - min(l2,ix) 65 | 66 | if d <= b1 and d <= b2: 67 | continue 68 | elif b1 < d and b1 <= b2: 69 | D[x][y] = b1 70 | U[x][y] = max(u1,ix) 71 | L[x][y] = min(l1,ix) 72 | else: 73 | D[x][y] = b2 74 | U[x][y] = max(u2,ix) 75 | L[x][y] = min(l2,ix) 76 | 77 | return True 78 | 79 | def mbd(img, num_iters): 80 | 81 | if len(img.shape) != 2: 82 | print('did not get 2d np array to fast mbd') 83 | return None 84 | if (img.shape[0] <= 3 or img.shape[1] <= 3): 85 | print('image is too small') 86 | return None 87 | 88 | L = np.copy(img) 89 | U = np.copy(img) 90 | D = float('Inf') * np.ones(img.shape) 91 | D[0,:] = 0 92 | D[-1,:] = 0 93 | D[:,0] = 0 94 | D[:,-1] = 0 95 | 96 | # unfortunately, iterating over numpy arrays is very slow 97 | img_list = img.tolist() 98 | L_list = L.tolist() 99 | U_list = U.tolist() 100 | D_list = D.tolist() 101 | 102 | for x in xrange(0,num_iters): 103 | if x%2 == 1: 104 | raster_scan(img_list,L_list,U_list,D_list) 105 | else: 106 | raster_scan_inv(img_list,L_list,U_list,D_list) 107 | 108 | return np.array(D_list) 109 | 110 | 111 | def get_saliency_mbd(input,method='b'): 112 | 113 | img_path_list = [] 114 | #we get either a filename or a list of filenames 115 | if type(input) == type(str()): 116 | img_path_list.append(input) 117 | elif type(input) == type(list()): 118 | img_path_list = input 119 | else: 120 | print('Input type is neither list or string') 121 | return None 122 | 123 | # Saliency map calculation based on: Minimum Barrier Salient Object Detection at 80 FPS 124 | for img_path in img_path_list: 125 | 126 | img = skimage.io.imread(img_path) 127 | img_mean = np.mean(img,axis=(2)) 128 | sal = mbd(img_mean,3) 129 | 130 | 131 | if method == 'b': 132 | # get the background map 133 | 134 | # paper uses 30px for an image of size 300px, so we use 10% 135 | (n_rows,n_cols,n_channels) = img.shape 136 | img_size = math.sqrt(n_rows * n_cols) 137 | border_thickness = int(math.floor(0.1 * img_size)) 138 | 139 | img_lab = img_as_float(skimage.color.rgb2lab(img)) 140 | 141 | px_left = img_lab[0:border_thickness,:,:] 142 | px_right = img_lab[n_rows - border_thickness-1:-1,:,:] 143 | 144 | px_top = img_lab[:,0:border_thickness,:] 145 | px_bottom = img_lab[:,n_cols - border_thickness-1:-1,:] 146 | 147 | px_mean_left = np.mean(px_left,axis=(0,1)) 148 | px_mean_right = np.mean(px_right,axis=(0,1)) 149 | px_mean_top = np.mean(px_top,axis=(0,1)) 150 | px_mean_bottom = np.mean(px_bottom,axis=(0,1)) 151 | 152 | 153 | px_left = px_left.reshape((n_cols*border_thickness,3)) 154 | px_right = px_right.reshape((n_cols*border_thickness,3)) 155 | 156 | px_top = px_top.reshape((n_rows*border_thickness,3)) 157 | px_bottom = px_bottom.reshape((n_rows*border_thickness,3)) 158 | 159 | cov_left = np.cov(px_left.T) 160 | cov_right = np.cov(px_right.T) 161 | 162 | cov_top = np.cov(px_top.T) 163 | cov_bottom = np.cov(px_bottom.T) 164 | 165 | cov_left = np.linalg.inv(cov_left) 166 | cov_right = np.linalg.inv(cov_right) 167 | 168 | cov_top = np.linalg.inv(cov_top) 169 | cov_bottom = np.linalg.inv(cov_bottom) 170 | 171 | 172 | u_left = np.zeros(sal.shape) 173 | u_right = np.zeros(sal.shape) 174 | u_top = np.zeros(sal.shape) 175 | u_bottom = np.zeros(sal.shape) 176 | 177 | u_final = np.zeros(sal.shape) 178 | img_lab_unrolled = img_lab.reshape(img_lab.shape[0]*img_lab.shape[1],3) 179 | 180 | px_mean_left_2 = np.zeros((1,3)) 181 | px_mean_left_2[0,:] = px_mean_left 182 | 183 | u_left = scipy.spatial.distance.cdist(img_lab_unrolled,px_mean_left_2,'mahalanobis', VI=cov_left) 184 | u_left = u_left.reshape((img_lab.shape[0],img_lab.shape[1])) 185 | 186 | px_mean_right_2 = np.zeros((1,3)) 187 | px_mean_right_2[0,:] = px_mean_right 188 | 189 | u_right = scipy.spatial.distance.cdist(img_lab_unrolled,px_mean_right_2,'mahalanobis', VI=cov_right) 190 | u_right = u_right.reshape((img_lab.shape[0],img_lab.shape[1])) 191 | 192 | px_mean_top_2 = np.zeros((1,3)) 193 | px_mean_top_2[0,:] = px_mean_top 194 | 195 | u_top = scipy.spatial.distance.cdist(img_lab_unrolled,px_mean_top_2,'mahalanobis', VI=cov_top) 196 | u_top = u_top.reshape((img_lab.shape[0],img_lab.shape[1])) 197 | 198 | px_mean_bottom_2 = np.zeros((1,3)) 199 | px_mean_bottom_2[0,:] = px_mean_bottom 200 | 201 | u_bottom = scipy.spatial.distance.cdist(img_lab_unrolled,px_mean_bottom_2,'mahalanobis', VI=cov_bottom) 202 | u_bottom = u_bottom.reshape((img_lab.shape[0],img_lab.shape[1])) 203 | 204 | max_u_left = np.max(u_left) 205 | max_u_right = np.max(u_right) 206 | max_u_top = np.max(u_top) 207 | max_u_bottom = np.max(u_bottom) 208 | 209 | u_left = u_left / max_u_left 210 | u_right = u_right / max_u_right 211 | u_top = u_top / max_u_top 212 | u_bottom = u_bottom / max_u_bottom 213 | 214 | u_max = np.maximum(np.maximum(np.maximum(u_left,u_right),u_top),u_bottom) 215 | 216 | u_final = (u_left + u_right + u_top + u_bottom) - u_max 217 | 218 | u_max_final = np.max(u_final) 219 | sal_max = np.max(sal) 220 | sal = sal / sal_max + u_final / u_max_final 221 | 222 | #postprocessing 223 | 224 | # apply centredness map 225 | sal = sal / np.max(sal) 226 | 227 | s = np.mean(sal) 228 | alpha = 50.0 229 | delta = alpha * math.sqrt(s) 230 | 231 | xv,yv = np.meshgrid(np.arange(sal.shape[1]),np.arange(sal.shape[0])) 232 | (w,h) = sal.shape 233 | w2 = w/2.0 234 | h2 = h/2.0 235 | 236 | C = 1 - np.sqrt(np.power(xv - h2,2) + np.power(yv - w2,2)) / math.sqrt(np.power(w2,2) + np.power(h2,2)) 237 | 238 | sal = sal * C 239 | 240 | #increase bg/fg contrast 241 | 242 | def f(x): 243 | b = 10.0 244 | return 1.0 / (1.0 + math.exp(-b*(x - 0.5))) 245 | 246 | fv = np.vectorize(f) 247 | 248 | sal = sal / np.max(sal) 249 | 250 | sal = fv(sal) 251 | 252 | return sal* 255.0 -------------------------------------------------------------------------------- /pyimgsaliency/saliency.py: -------------------------------------------------------------------------------- 1 | import math 2 | import sys 3 | import operator 4 | import networkx as nx 5 | #import matplotlib.pyplot as plt 6 | import numpy as np 7 | import scipy.spatial.distance 8 | import scipy.signal 9 | import skimage 10 | import skimage.io 11 | from skimage.segmentation import slic 12 | from skimage.util import img_as_float 13 | from scipy.optimize import minimize 14 | 15 | import pdb 16 | 17 | def S(x1,x2,geodesic,sigma_clr=10): 18 | return math.exp(-pow(geodesic[x1,x2],2)/(2*sigma_clr*sigma_clr)) 19 | 20 | def compute_saliency_cost(smoothness,w_bg,wCtr): 21 | n = len(w_bg) 22 | A = np.zeros((n,n)) 23 | b = np.zeros((n)) 24 | 25 | for x in xrange(0,n): 26 | A[x,x] = 2 * w_bg[x] + 2 * (wCtr[x]) 27 | b[x] = 2 * wCtr[x] 28 | for y in xrange(0,n): 29 | A[x,x] += 2 * smoothness[x,y] 30 | A[x,y] -= 2 * smoothness[x,y] 31 | 32 | x = np.linalg.solve(A, b) 33 | 34 | return x 35 | 36 | def path_length(path,G): 37 | dist = 0.0 38 | for i in xrange(1,len(path)): 39 | dist += G[path[i - 1]][path[i]]['weight'] 40 | return dist 41 | 42 | def make_graph(grid): 43 | # get unique labels 44 | vertices = np.unique(grid) 45 | 46 | # map unique labels to [1,...,num_labels] 47 | reverse_dict = dict(zip(vertices,np.arange(len(vertices)))) 48 | grid = np.array([reverse_dict[x] for x in grid.flat]).reshape(grid.shape) 49 | 50 | # create edges 51 | down = np.c_[grid[:-1, :].ravel(), grid[1:, :].ravel()] 52 | right = np.c_[grid[:, :-1].ravel(), grid[:, 1:].ravel()] 53 | all_edges = np.vstack([right, down]) 54 | all_edges = all_edges[all_edges[:, 0] != all_edges[:, 1], :] 55 | all_edges = np.sort(all_edges,axis=1) 56 | num_vertices = len(vertices) 57 | edge_hash = all_edges[:,0] + num_vertices * all_edges[:, 1] 58 | # find unique connections 59 | edges = np.unique(edge_hash) 60 | # undo hashing 61 | edges = [[vertices[x%num_vertices], 62 | vertices[x/num_vertices]] for x in edges] 63 | 64 | return vertices, edges 65 | 66 | 67 | def get_saliency_rbd(img_path): 68 | 69 | # Saliency map calculation based on: 70 | # Saliency Optimization from Robust Background Detection, Wangjiang Zhu, Shuang Liang, Yichen Wei and Jian Sun, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2014 71 | 72 | img = skimage.io.imread(img_path) 73 | 74 | if len(img.shape) != 3: # got a grayscale image 75 | img = skimage.color.gray2rgb(img) 76 | 77 | img_lab = img_as_float(skimage.color.rgb2lab(img)) 78 | 79 | img_rgb = img_as_float(img) 80 | 81 | img_gray = img_as_float(skimage.color.rgb2gray(img)) 82 | 83 | segments_slic = slic(img_rgb, n_segments=250, compactness=10, sigma=1, enforce_connectivity=False) 84 | 85 | num_segments = len(np.unique(segments_slic)) 86 | 87 | nrows, ncols = segments_slic.shape 88 | max_dist = math.sqrt(nrows*nrows + ncols*ncols) 89 | 90 | grid = segments_slic 91 | 92 | (vertices,edges) = make_graph(grid) 93 | 94 | gridx, gridy = np.mgrid[:grid.shape[0], :grid.shape[1]] 95 | 96 | centers = dict() 97 | colors = dict() 98 | distances = dict() 99 | boundary = dict() 100 | 101 | for v in vertices: 102 | centers[v] = [gridy[grid == v].mean(), gridx[grid == v].mean()] 103 | colors[v] = np.mean(img_lab[grid==v],axis=0) 104 | 105 | x_pix = gridx[grid == v] 106 | y_pix = gridy[grid == v] 107 | 108 | if np.any(x_pix == 0) or np.any(y_pix == 0) or np.any(x_pix == nrows - 1) or np.any(y_pix == ncols - 1): 109 | boundary[v] = 1 110 | else: 111 | boundary[v] = 0 112 | 113 | G = nx.Graph() 114 | 115 | #buid the graph 116 | for edge in edges: 117 | pt1 = edge[0] 118 | pt2 = edge[1] 119 | color_distance = scipy.spatial.distance.euclidean(colors[pt1],colors[pt2]) 120 | G.add_edge(pt1, pt2, weight=color_distance ) 121 | 122 | #add a new edge in graph if edges are both on boundary 123 | for v1 in vertices: 124 | if boundary[v1] == 1: 125 | for v2 in vertices: 126 | if boundary[v2] == 1: 127 | color_distance = scipy.spatial.distance.euclidean(colors[v1],colors[v2]) 128 | G.add_edge(v1,v2,weight=color_distance) 129 | 130 | geodesic = np.zeros((len(vertices),len(vertices)),dtype=float) 131 | spatial = np.zeros((len(vertices),len(vertices)),dtype=float) 132 | smoothness = np.zeros((len(vertices),len(vertices)),dtype=float) 133 | adjacency = np.zeros((len(vertices),len(vertices)),dtype=float) 134 | 135 | sigma_clr = 10.0 136 | sigma_bndcon = 1.0 137 | sigma_spa = 0.25 138 | mu = 0.1 139 | 140 | all_shortest_paths_color = nx.shortest_path(G,source=None,target=None,weight='weight') 141 | 142 | for v1 in vertices: 143 | for v2 in vertices: 144 | if v1 == v2: 145 | geodesic[v1,v2] = 0 146 | spatial[v1,v2] = 0 147 | smoothness[v1,v2] = 0 148 | else: 149 | geodesic[v1,v2] = path_length(all_shortest_paths_color[v1][v2],G) 150 | spatial[v1,v2] = scipy.spatial.distance.euclidean(centers[v1],centers[v2]) / max_dist 151 | smoothness[v1,v2] = math.exp( - (geodesic[v1,v2] * geodesic[v1,v2])/(2.0*sigma_clr*sigma_clr)) + mu 152 | 153 | for edge in edges: 154 | pt1 = edge[0] 155 | pt2 = edge[1] 156 | adjacency[pt1,pt2] = 1 157 | adjacency[pt2,pt1] = 1 158 | 159 | for v1 in vertices: 160 | for v2 in vertices: 161 | smoothness[v1,v2] = adjacency[v1,v2] * smoothness[v1,v2] 162 | 163 | area = dict() 164 | len_bnd = dict() 165 | bnd_con = dict() 166 | w_bg = dict() 167 | ctr = dict() 168 | wCtr = dict() 169 | 170 | for v1 in vertices: 171 | area[v1] = 0 172 | len_bnd[v1] = 0 173 | ctr[v1] = 0 174 | for v2 in vertices: 175 | d_app = geodesic[v1,v2] 176 | d_spa = spatial[v1,v2] 177 | w_spa = math.exp(- ((d_spa)*(d_spa))/(2.0*sigma_spa*sigma_spa)) 178 | area_i = S(v1,v2,geodesic) 179 | area[v1] += area_i 180 | len_bnd[v1] += area_i * boundary[v2] 181 | ctr[v1] += d_app * w_spa 182 | bnd_con[v1] = len_bnd[v1] / math.sqrt(area[v1]) 183 | w_bg[v1] = 1.0 - math.exp(- (bnd_con[v1]*bnd_con[v1])/(2*sigma_bndcon*sigma_bndcon)) 184 | 185 | for v1 in vertices: 186 | wCtr[v1] = 0 187 | for v2 in vertices: 188 | d_app = geodesic[v1,v2] 189 | d_spa = spatial[v1,v2] 190 | w_spa = math.exp(- (d_spa*d_spa)/(2.0*sigma_spa*sigma_spa)) 191 | wCtr[v1] += d_app * w_spa * w_bg[v2] 192 | 193 | # normalise value for wCtr 194 | 195 | min_value = min(wCtr.values()) 196 | max_value = max(wCtr.values()) 197 | 198 | minVal = [key for key, value in wCtr.iteritems() if value == min_value] 199 | maxVal = [key for key, value in wCtr.iteritems() if value == max_value] 200 | 201 | for v in vertices: 202 | wCtr[v] = (wCtr[v] - min_value)/(max_value - min_value) 203 | 204 | img_disp1 = img_gray.copy() 205 | img_disp2 = img_gray.copy() 206 | 207 | x = compute_saliency_cost(smoothness,w_bg,wCtr) 208 | 209 | for v in vertices: 210 | img_disp1[grid == v] = x[v] 211 | 212 | img_disp2 = img_disp1.copy() 213 | sal = np.zeros((img_disp1.shape[0],img_disp1.shape[1],3)) 214 | 215 | sal = img_disp2 216 | sal_max = np.max(sal) 217 | sal_min = np.min(sal) 218 | sal = 255 * ((sal - sal_min) / (sal_max - sal_min)) 219 | 220 | return sal 221 | 222 | def get_saliency_ft(img_path): 223 | 224 | # Saliency map calculation based on: 225 | 226 | img = skimage.io.imread(img_path) 227 | 228 | img_rgb = img_as_float(img) 229 | 230 | img_lab = skimage.color.rgb2lab(img_rgb) 231 | 232 | mean_val = np.mean(img_rgb,axis=(0,1)) 233 | 234 | kernel_h = (1.0/16.0) * np.array([[1,4,6,4,1]]) 235 | kernel_w = kernel_h.transpose() 236 | 237 | blurred_l = scipy.signal.convolve2d(img_lab[:,:,0],kernel_h,mode='same') 238 | blurred_a = scipy.signal.convolve2d(img_lab[:,:,1],kernel_h,mode='same') 239 | blurred_b = scipy.signal.convolve2d(img_lab[:,:,2],kernel_h,mode='same') 240 | 241 | blurred_l = scipy.signal.convolve2d(blurred_l,kernel_w,mode='same') 242 | blurred_a = scipy.signal.convolve2d(blurred_a,kernel_w,mode='same') 243 | blurred_b = scipy.signal.convolve2d(blurred_b,kernel_w,mode='same') 244 | 245 | im_blurred = np.dstack([blurred_l,blurred_a,blurred_b]) 246 | 247 | sal = np.linalg.norm(mean_val - im_blurred,axis = 2) 248 | sal_max = np.max(sal) 249 | sal_min = np.min(sal) 250 | sal = 255 * ((sal - sal_min) / (sal_max - sal_min)) 251 | return sal 252 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------