Python图像超分割SLIC算法 计算邻接矩阵及邻接列表
程序员文章站
2022-07-08 20:27:11
获得每个超像素对应的像素索引sp_label_matrix=fs.slic(img_rgb, n_segments=400, compactness=10, sigma=1, enforce_connectivity=False)sp_label_vector=sp_label_matrix.reshape(1,-1)sp_num=len(np.unique(sp_label_matrix))sp_ind=np.empty((sp_num,2),dtype=object)for i in r...
Obtain the pixel indices of each superpixel
sp_label_matrix=fs.slic(img_rgb, n_segments=400, compactness=10, sigma=1, enforce_connectivity=False)
sp_label_vector=sp_label_matrix.reshape(1,-1)
sp_num=len(np.unique(sp_label_matrix))
sp_ind=np.empty((sp_num,2),dtype=object)
for i in range(sp_num):
sp_ind[i,:]=np.where(sp_label_vector==i)
compute the feature representation for each superpixel and form a feature matrix(行数为特征维度,列数为超像素个数)
def compute_sp_feature_matrix(np_img,sp_ind):
gray_feature=np_img.reshape(1,-1)
median_feature=cv2.medianBlur(np.float32(np_img),3).reshape(1,-1)
average_feature=cv2.blur(np_img,(3,3)).reshape(1,-1)
feature_matrix=np.concatenate((gray_feature,median_feature,average_feature),axis=0)
rows,cols=feature_matrix.shape
sp_num=sp_ind.shape[0]
sp_feature_matrix=np.empty((rows,sp_num))
for i in range(sp_num):
sub_matrix=feature_matrix[:,sp_ind[i,1]]
sp_feature_matrix[:,i]=np.mean(sub_matrix,axis=1)
return sp_feature_matrix
compute the adjacent matrix and adjacent list
def compute_sp_adjacency(sp_label_matrix):
labels=np.unique(sp_label_matrix)
sp_num=len(labels)
# adjacent matrix
am=np.zeros((sp_num,sp_num))
# adjacent list
al=np.empty((sp_num,1),dtype=object)
for i in range(sp_num):
r=np.zeros(shape=sp_label_matrix.shape,dtype=np.uint8)
r[sp_label_matrix==i]=1
r_dilate_one_pixel=cv2.dilate(r,np.ones((3,3),dtype=np.uint8))
r_boundary=r_dilate_one_pixel-r
cur_adj=np.unique(np.setdiff1d(r_boundary*sp_label_matrix,[0]))
al[i,0]=cur_adj
am[i,cur_adj]=1
return am,al
本文地址:https://blog.csdn.net/jzwong/article/details/107651872
上一篇: 冬天吃什么食物最好 冬季养生食物推荐
下一篇: 冬季养生 小雪节气多吃“三黑”