基于skimage提取根菜长宽时如何消除须根干扰获取最长填充轴长度
解决方案
方案1:形态学预处理消除根须干扰(推荐,实现更简单)
你遇到的根须干扰属于细小突出噪声,直接用形态学开运算就可以在保留根体主体形状的前提下磨掉细根须,之后再调用measure.regionprops_table就能得到准确的尺寸,不需要额外写逻辑。
你可以在fillh2 = morphology.remove_small_objects(fillh, 100000)之后加一步开运算:
# 开运算去除细小根须,disk半径可根据根须粗细调整,一般2-5即可 selem = morphology.disk(3) fillh2_processed = morphology.opening(fillh2, selem)
之后用处理后的fillh2_processed去算连通域和参数即可。
方案2:按最长连续填充段计算边界的自定义实现
目前没有直接对应该需求的现成函数,你可以参考下面的自定义函数实现逻辑:
函数的核心逻辑:
- 统计所有行的最长连续前景像素长度,取最长的那一行的连续段起止列作为根体的左右边界(min_col、max_col)
- 统计所有列的最长连续前景像素长度,取最长的那一列的连续段起止行作为根体的上下边界(min_row、max_row)
代码实现
def get_main_body_bbox(binary_img): # binary_img是二值分割图,前景为True/1,背景为False/0 rows, cols = binary_img.shape # 计算左右边界:遍历所有行找最长连续前景段 max_row_continuous_len = 0 best_col_start, best_col_end = 0, 0 for r in range(rows): row_data = binary_img[r, :] # 找所有连续前景段的起止位置 pixel_pad = np.pad(row_data, (1, 1), mode='constant', constant_values=0) diff = np.diff(pixel_pad) starts = np.where(diff == 1)[0] ends = np.where(diff == -1)[0] if len(starts) == 0: continue # 找当前行最长的段 current_max_len = np.max(ends - starts) current_max_idx = np.argmax(ends - starts) if current_max_len > max_row_continuous_len: max_row_continuous_len = current_max_len best_col_start = starts[current_max_idx] best_col_end = ends[current_max_idx] - 1 # 计算上下边界:遍历所有列找最长连续前景段 max_col_continuous_len = 0 best_row_start, best_row_end = 0, 0 for c in range(cols): col_data = binary_img[:, c] pixel_pad = np.pad(col_data, (1, 1), mode='constant', constant_values=0) diff = np.diff(pixel_pad) starts = np.where(diff == 1)[0] ends = np.where(diff == -1)[0] if len(starts) == 0: continue current_max_len = np.max(ends - starts) current_max_idx = np.argmax(ends - starts) if current_max_len > max_col_continuous_len: max_col_continuous_len = current_max_len best_row_start = starts[current_max_idx] best_row_end = ends[current_max_idx] - 1 return best_row_start, best_row_end, best_col_start, best_col_end
使用方法
得到最大连通域的二值图largest之后直接调用即可:
min_row, max_row, min_col, max_col = get_main_body_bbox(largest) # 计算长宽 height = max_row - min_row + 1 width = max_col - min_col + 1
内容的提问来源于stack exchange,提问作者blopblop
相关产品推荐
相关产品推荐

