Python实现MATLAB函数regionprops(BW, ‘Extrema’)功能
Python软件包skimage中的measure.regionprops()与MATLAB函数regionprops()功能相似。
返回二值化图像区域顶点坐标MATLAB中使用的是regionprops(BW,‘Extrema’),可以返回八个顶点坐标,如图1所示。而Python中measure.regionprops(BW)[‘bbox’]只返回四个顶点坐标(min_row,min_col,max_row,max_col)。
图1 MATLAB中regionprops(BW,‘Extrema’)返回的8个顶点
为了在Python上实现与MATLAB函数regionprops(BW,‘Extrema’)完全一致的返回结果,可以在利用measure.regionprops(BW)[‘bbox’]的基础上做如下修改:
import numpy as np
from skimage import measure
def regionprops(img,feature):
if feature=='bbox':
min_row,min_col,max_row,max_col = measure.regionprops(img.astype('uint8'))[0][feature]
max_row = max_row-1
max_col = max_col-1
# top都是.min(),bottom都是.max(),因为相同列的情况下,前面的行更小(更靠上)
valid_pixel = np.argwhere(img>0)
left_top = valid_pixel[np.argwhere(valid_pixel[:,1]==min_col).min(),:]
left_bottom = valid_pixel[np.argwhere(valid_pixel[:,1]==min_col).max(),:]
right_top = valid_pixel[np.argwhere(valid_pixel[:,1]==max_col).min(),:]
right_bottom = valid_pixel[np.argwhere(valid_pixel[:,1]==max_col).max(),:]
LeftTop = left_top.astype('float')+1.-0.5 # +1是因为索引从0开始
LeftBottom = left_bottom.copy().astype('float')
LeftBottom[0] = left_bottom[0].astype('float')+1.+0.5
LeftBottom[1] = left_bottom[1].astype('float')+1.-0.5
RightTop = right_top.copy().astype('float')
RightTop[0] = right_top[0].astype('float')+1.-0.5
RightTop[1] = right_top[1].astype('float')+1.+0.5
RightBottom = right_bottom.astype('float')+1.+0.5
# left都是.min(),因为相同行的情况下前面行的列索引更小(就是更偏左),right都是.max()
top_left = valid_pixel[np.argwhere(valid_pixel[:,0]==min_row).min(),:]
bottom_left = valid_pixel[np.argwhere(valid_pixel[:,0]==max_row).min(),:]
top_right = valid_pixel[np.argwhere(valid_pixel[:,0]==min_row).max(),:]
bottom_right = valid_pixel[np.argwhere(valid_pixel[:,0]==max_row).max(),:]
TopLeft = top_left.astype('float')+1-0.5
BottomLeft = bottom_left.copy().astype('float')
BottomLeft[0] = bottom_left[0].astype('float')+1.+0.5
BottomLeft[1] = bottom_left[1].astype('float')+1.-0.5
TopRight = top_right.copy().astype('float')
TopRight[0] = top_right[0].astype('float')+1.-0.5
TopRight[1] = top_right[1].astype('float')+1.+0.5
BottomRight = bottom_right.astype('float')+1.+0.5
STATS = {
'TopLeft':TopLeft,
'TopRight':TopRight,
'RightTop':RightTop,
'RightBottom':RightBottom,
'BottomRight':BottomRight,
'BottomLeft':BottomLeft,
'LeftBottom':LeftBottom,
'LeftTop':LeftTop
}
return STATS