摘要
本文是研究生课程图像处理期末作业,内容是了解并入门超像素算法原理,主要介绍了超像素的评测标准,经典算法 SLIC,讨论了 SLIC 算法中的不足之处,以及 SLIC 的两个有效的改进算法 SEEDS 和 ETPS。
文章内容见我的码云
python3 代码
运算速度慢但是便于理清 SLIC 算法的参考实现
import math
from skimage import io, color
import numpy as np
from tqdm import trange
from tqdm import tqdm
class Cluster(object):
cluster_index = 1
def __init__(self, h, w, l=0, a=0, b=0):
self.update(h, w, l, a, b)
self.pixels = []
self.no = self.cluster_index
Cluster.cluster_index += 1
def update(self, h, w, l, a, b):
self.h = h
self.w = w
self.l = l
self.a = a
self.b = b
def __str__(self):
return "{},{}:{} {} {} ".format(self.h, self.w, self.l, self.a, self.b)
def __repr__(self):
return self.__str__()
class SLICProcessor(object):
@staticmethod
def open_image(path):
"""
Return:
3D array, row col [LAB]
"""
rgb = io.imread(path)
lab_arr = color.rgb2lab(rgb)
return lab_arr
@staticmethod
def save_lab_image(path, lab_arr):
"""
Convert the array to RBG, then save the image
:param path:
:param lab_arr:
:return:
"""
rgb_arr = color.lab2rgb(lab_arr)
io.imsave(path, rgb_arr)
def make_cluster(self, h, w):
h = int(h)
w = int(w)
return Cluster(h, w,
self.data[h][w][0],
self.data[h][w][1],
self.data[h][w][2])
def __init__(self, filename, K, M):
self.K = K
self.M = M
self.data = self.open_image(filename)
self.image_height = self.data.shape[0]
self.image_width = self.data.shape[1]
self.N = self.image_height * self.image_width
self.S = int(math.sqrt(self.N / self.K))
self.clusters = []
self.label = {
}
self.dis = np.full((self.image_height, self.image_width), np.inf)
def init_clusters(self):
h = self.S // 2
w = self.S // 2
while h < self.image_height:
while w < self.image_width:
self.clusters.append(self.make_cluster(h, w))
w += self.S
w = self.S // 2
h += self.S
def get_gradient(self, h, w):
if w + 1 >= self.image_width:
w = self.image_width - 2
if h + 1 >= self.image_height:
h = self.image_height - 2
gradient = self.data[h + 1][w + 1][0] - self.data[h][w][0] + \
self.data[h + 1