通过两点坐标可直接选定范围,这基本不是问题,主要是需要对范围进行适当扩充,需要做一些其他处理,在这记录一下代码思路供后续升级使用。
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))