两点坐标选定指定大小的图像范围

说明

通过两点坐标可直接选定范围,这基本不是问题,主要是需要对范围进行适当扩充,需要做一些其他处理,在这记录一下代码思路供后续升级使用。
两点坐标选定指定大小的图像范围_第1张图片

操作考量

  1. 操作参数输入合法
  2. 范围扩充指定大小
  3. 保证选定区域在图像合法范围内

代码实现

  1. 将输入的两点重新定位为指定范围的左上、右下两点
  2. 选中范围两边分别向外扩充
  3. 处理边界非法情况,对整个扩充的范围进行移动
def field_expand(point1: tuple, point2: tuple, max_boundary_pixel: int, expand_size: int):
    """
    Expand the field in legal boundary(apply to square image now)
    
    Example: 
    (6, 3), (2, 5) expand outward 2(expand_size:2) and boundary 8(max_boundary_pixel:7)
    result: (1, 2), (7, 6)
    :param point1: 
    :param point2: 
    :param max_boundary_pixel: 
    :param expand_size: 
    :return: 
    """
    # redefine the point(as northwest and southeast point)
    x1, y1 = point1
    x2, y2 = point2
    if x1 > x2:
        x1, x2 = x2, x1
    if y1 > y2:
        y1, y2 = y2, y1

    assert x2 - x1 > 0 and y2 - y1 > 0, f'\033[1;31m Points illegal\033[0m'
    assert y2 - y1 + expand_size < max_boundary_pixel and x2 - x1 + expand_size < max_boundary_pixel, \
        f'\033[1;31m Expanded field out of max_boundary_pixel\033[0m'

    # expand
    half_expand_size = expand_size // 2
    x1_tmp = x1 - half_expand_size
    y1_tmp = y1 - half_expand_size
    x2_tmp = x2 + expand_size - half_expand_size
    y2_tmp = y2 + expand_size - half_expand_size

    # ensure the expanded field is legal
    if x1_tmp < 0:
        x2_tmp -= x1_tmp
        x1_tmp = 0
    if y1_tmp < 0:
        y2_tmp -= y1_tmp
        y1_tmp = 0

    if x2_tmp > max_boundary_pixel:
        x1_tmp -= (x2_tmp - max_boundary_pixel)
        x2_tmp = max_boundary_pixel
    if y2_tmp > max_boundary_pixel:
        y1_tmp -= (y2_tmp - max_boundary_pixel)
        y2_tmp = max_boundary_pixel
    return (x1_tmp, y1_tmp), (x2_tmp, y2_tmp)


if __name__ == '__main__':
    print(field_expand((6, 3), (2, 5), 7, 2))

你可能感兴趣的:(图像处理,python,图像处理)