含有无效区域的图像裁剪

图像中有一些区域是无效区域(值为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
相关推荐
霍志杰3 分钟前
记一次csv和xlsx之间的转换处理
python
测试199818 分钟前
Jmeter是如何实现接口关联的?
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·接口测试
小蕾Java30 分钟前
PyCharm 2025:最新使用图文教程!
ide·python·pycharm
java1234_小锋41 分钟前
TensorFlow2 Python深度学习 - 卷积神经网络(CNN)介绍
python·深度学习·tensorflow·tensorflow2
java1234_小锋43 分钟前
TensorFlow2 Python深度学习 - 循环神经网络(RNN)- 简介
python·深度学习·tensorflow·tensorflow2
大飞记Python1 小时前
Chromedriver放项目里就行!Selenium 3 和 4 指定路径方法对比 + 兼容写法
开发语言·python
小薛引路1 小时前
office便捷办公06:根据相似度去掉excel中的重复行
windows·python·excel
Hs_QY_FX1 小时前
Python 分类模型评估:从理论到实战(以信用卡欺诈检测为例)
人工智能·python·机器学习·数据挖掘·多分类评估
Gitpchy1 小时前
Day 18 推断聚类后簇的类型
python·机器学习·聚类
查士丁尼·绵1 小时前
笔试-基站维护
python