求mask的最大连通域 并且标记连通区域边界

该代码实现从掩膜图中找出最大连通分量并进行保留,同时进行边界跟踪,删除特定条件的点,最后输出连通分量的边界点。使用了OpenCV库进行图像处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入:

一张掩膜图

输出:

该掩膜的边界点,顺序表示

最大连通分量

输入一张mask 有多个连通分量
输出一个mask 只有一个最大的连通分量

def findmax(path):

    # 图像读取
    imagePath = path
    img = cv2.imread(imagePath, 0)
    ret, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
    # cv2.imwrite('binary.png', img)


    # # 图像实例化
    img = measure.label(img, connectivity=1)  #4连通
    props = measure.regionprops(img)
    # cv2.imwrite('binary1.png', img)

    #
    # 最大区域获取
    max_area = 0
    max_index = 0
    # props只包含像素值不为零区域的属性,因此index要从1开始
    for index, prop in enumerate(props, start=1):
        if prop.area > max_area:
            max_area = prop.area
            # index 代表每个联通区域内的像素值;prop.area代表相应连通区域内的像素个数
            max_index = index

    img[img != max_index] = 0
    img[img == max_index] = 255
    # img = np.array(img,dtype='uint8')


    return img

边界跟踪

在这里插入图片描述

在这里插入图片描述

def edge(img):
    # edge = cv2.imread(r"D:\project\lab\badminton\chafen\final1.png", 0)
    img_list = img.tolist()
    # print(edge.shape)
    flag = 0
    for i in range(1, img.shape[0] - 1): # 将单独特殊点删除 否则影响后续标记
        for j in range(1, img.shape[1] - 1):  # w 列
            if img_list[i + 1][j]  + img_list[i + 1][j - 1] + img_list[i + 1][j + 1]\
                    + img_list[i][j + 1]+ img_list[i][j - 1]\
                    + img_list[i - 1][j]+ img_list[i - 1][j + 1]+ img_list[i - 1][j - 1] == 255:
                img_list[i][j] = 0

    for i in range(1, img.shape[0] - 1):  # 找到起始点
        for j in range(1, img.shape[1] - 1):  # w 列
            if img_list[i][j] == 255:
                flag = 1
                print(i, j)
                break
        if flag == 1:
            break

    flag_list = np.zeros(img.shape)
    list1 = []
    b = True
    dirs = [[0, 0], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]]
    while 1:
        for m in range(0, 11):
            try:
                if img_list[i + dirs[m][0]][j + dirs[m][1]] == 0:
                    b = True
                if img_list[i + dirs[m][0]][j + dirs[m][1]] == 255 and flag_list[i + dirs[m][0]][
                    j + dirs[m][1]] == 0 and b == True:
                    list1.append([j + dirs[m][1], i + dirs[m][0]])
                    flag_list[i + dirs[m][0]][j + dirs[m][1]] = 255
                    i = i + dirs[m][0]
                    j = j + dirs[m][1]
                    b = False
                    break
            except:
                cv2.imwrite('shuzu.png', flag_list)
                return list1
function connect_bw = Connect_bw(bw) tic result_img = zeros(size(bw)); %% 提取所有连边界 B = bwboundaries(bw, 'noholes'); if isempty(B) error('未检测到连'); end %% 计算各连面积并排序 boundary_sizes = cellfun(@(x) size(x,1), B); [~, sorted_indices] = sort(boundary_sizes, 'descend'); top5_indices = sorted_indices(1:min(5, length(B))); %% 创建可视化窗口 figure; imshow(bw); hold on; %% 遍历每个连 for k = 1:length(B) %% 获取当前连边界 boundary = B{k}; x = boundary(:, 2); % 列坐标对应x轴 y = boundary(:, 1); % 行坐标对应y轴 %% 动态设置百分比 if ismember(k, top5_indices) percentage = 0.1; % 前5大用10% else percentage = 0.4; % 其他用40% end %% PCA分析确定主方向 coords = [x, y]; mu = mean(coords); [coeff, ~, ~] = pca(coords - mu); main_dir = coeff(:, 1); % 第一主成分方向 %% 标注主轴中心点(使用五角星标记) % scatter(mu(1), mu(2), 150, 'm', 'p', 'filled'); % 洋红色五角星 %% 投影计算与区域划分 centered_coords = coords - mu; projection = centered_coords * main_dir; %% 根据动态百分比选择边界点 % 左侧处理 left_mask = projection <= 0; left_coords = coords(left_mask, :); left_dist = abs(projection(left_mask)); [~, idx] = sort(left_dist, 'descend'); select_num = max(ceil(percentage*length(left_dist)), 1); left_selected = left_coords(idx(1:select_num), :); % 右侧处理 right_mask = projection > 0; right_coords = coords(right_mask, :); right_dist = abs(projection(right_mask)); [~, idx] = sort(right_dist, 'descend'); select_num = max(ceil(percentage*length(right_dist)), 1); right_selected = right_coords(idx(1:select_num), :); %% 在全黑图像上标记点 % 标记左侧点 if ~isempty(left_selected) for i = 1:size(left_selected,1) col = left_selected(i,1); % x坐标(列索引) row = left_selected(i,2); % y坐标(行索引) result_img(row, col) = 1; end end % 标记右侧点 if ~isempty(right_selected) for i = 1:size(right_selected,1) col = right_selected(i,1); % x坐标(列索引) row = right_selected(i,2); % y坐标(行索引) result_img(row, col) = 1; end end %% 绘制当前连结果 % plot(x, y, 'g', 'LineWidth', 1.5); % 绘制边界 % scatter(left_selected(:,1), left_selected(:,2), 30, 'r', 'filled'); % scatter(right_selected(:,1), right_selected(:,2), 30, 'b', 'filled'); end % hold off; result_img = connect(result_img); connect_bw = result_img|bw; % imshow(connect_bw) toc end
03-25
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值