含有无效区域的图像裁剪

图像中有一些区域是无效区域(值为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
相关推荐
java1234_小锋23 分钟前
一周学会Flask3 Python Web开发-客户端状态信息Cookie以及加密
前端·python·flask·flask3
B站计算机毕业设计超人1 小时前
计算机毕业设计Python+DeepSeek-R1高考推荐系统 高考分数线预测 大数据毕设(源码+LW文档+PPT+讲解)
大数据·python·机器学习·网络爬虫·课程设计·数据可视化·推荐算法
winfredzhang2 小时前
Python实战:Excel中文转拼音工具开发教程
python·安全·excel·汉字·pinyin·缩写
奔跑吧邓邓子2 小时前
【Python爬虫(34)】Python多进程编程:开启高效并行世界的钥匙
开发语言·爬虫·python·多进程
wang_yb3 小时前
『Python底层原理』--Python属性的工作原理
python·databook
量化投资技术3 小时前
【量化策略】趋势跟踪策略
python·量化交易·量化·量化投资·qmt·miniqmt
伊一大数据&人工智能学习日志3 小时前
自然语言处理NLP 04案例——苏宁易购优质评论与差评分析
人工智能·python·机器学习·自然语言处理·数据挖掘
刀客1233 小时前
python3+TensorFlow 2.x(六)自编码器
人工智能·python·tensorflow
微刻时光3 小时前
影刀RPA中级证书-Excel进阶-开票清单
经验分享·python·低代码·rpa·影刀·影刀证书·影刀实战
一朵小花4 小时前
Python中with的用法
python