Python Superpixel SLICアルゴリズム隣接マトリクスおよび隣接リスト
1744 ワード
Obtain the pixel indices of each superpixel
compute the feature representation for each superpixel and forma feature matrix(行数は特徴次元、列数は超画素個数)
compute the adjacent matrix and adjacent list
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 forma 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