含有无效区域的图像裁剪

图像中有一些区域是无效区域(值为0),希望将图像裁剪成多个小块且每个小块不包含无效区域

c 复制代码
def count_consecutive_ones(binary_string, k):
    # 将字符串转换为 NumPy 数组
    binary_array = np.array(list(binary_string), dtype=int)

    # 找到所有 1 的位置
    ones_positions = np.where(binary_array == 1)[0]

    if len(ones_positions) == 0:
        return [], []

    # 找到连续 1 的断点,差值大于1的地方
    split_indices = np.diff(ones_positions) > 1

    # 分割出每段连续 1 的位置数组
    segment_indices = np.split(ones_positions, np.where(split_indices)[0] + 1)

    # 计算每段连续 1 的长度
    segment_lengths = [len(segment) for segment in segment_indices if len(segment) > k]

    # 找出长度大于 k 的段的起始位置
    long_segment_pos = [(segment[0], segment[-1]) for segment in segment_indices if len(segment) > k]

    return segment_lengths, long_segment_pos


def split_image_into_patches_special(image, patch_size, stride):
    """
    将图像划分为多个 patch,且图像不包含0

    参数:
    - image: 输入图像
    - patch_size: 每个 patch 的大小,以元组 (height, width) 形式给出

    返回:
    - patches: 包含所有 patch 的列表
    """
    mask = image.sum(-1) > 0
    # left, right = np.where(mask.sum(0) > patch_size[0])[0], np.where(mask.sum(0) > patch_size[0])[-1]
    # top, bottom = np.where(mask.sum(1) > patch_size[1])[0], np.where(mask.sum(1) > patch_size[1])[-1]

    current_top = np.where(mask.sum(1) > patch_size)[0][0]
    patches = []
    while True:
        long_segment_pos = []
        for t in range(current_top, len(image) - stride + 1):
            segment_lengths, long_segment_pos = count_consecutive_ones(mask[t], k=stride)
            if len(segment_lengths) > 0:
                current_top = t
                break

        if len(long_segment_pos) == 0:
            break

        for current_start, current_end in long_segment_pos:
            for x in range(current_start, current_end-patch_size+1, stride):
                patch = image[current_top:current_top + patch_size, x:x + patch_size]
                mask[current_top:current_top + patch_size, x:x + patch_size] = 0
                patches.append(patch)


    return patches
相关推荐
都叫我大帅哥43 分钟前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`3 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿5 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
杭州杭州杭州6 小时前
Python笔记
开发语言·笔记·python
路人蛃8 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
qiqiqi(^_×)8 小时前
卡在“pycharm正在创建帮助程序目录”
ide·python·pycharm
Ching·8 小时前
esp32使用ESP-IDF在Linux下的升级步骤,和遇到的坑Traceback (most recent call last):,及解决
linux·python·esp32·esp_idf升级
吗喽1543451889 小时前
用python实现自动化布尔盲注
数据库·python·自动化
hbrown9 小时前
Flask+LayUI开发手记(十一):选项集合的数据库扩展类
前端·数据库·python·layui
猫头虎9 小时前
什么是 npm、Yarn、pnpm? 有什么区别? 分别适应什么场景?
前端·python·scrapy·arcgis·npm·beautifulsoup·pip