[英]python remove rectangles from list in loop by distance
我有一个表示python中的矩形的对象,如下所示:
class cords:
x_start = -1
x_end = -1
y_start = -1
y_end = -1
def __init__(self, x_start, x_end, y_start, y_end):
self.x_start = x_start
self.x_end = x_end
self.y_start = y_start
self.y_end = y_end
现在我有一个名为new_cords
的cords
列表,其值如下:
x_start: 508, x_end: 530, y_start: 843, y_end: 869
x_start: 508, x_end: 530, y_start: 843, y_end: 870
x_start: 401, x_end: 451, y_start: 582, y_end: 620
x_start: 467, x_end: 513, y_start: 583, y_end: 621
x_start: 466, x_end: 512, y_start: 634, y_end: 672
x_start: 533, x_end: 585, y_start: 534, y_end: 561
x_start: 528, x_end: 576, y_start: 583, y_end: 622
我想从new_cords
删除彼此相距3
矩形以减少相似的矩形。
我写了这个:
for c_out in new_cords:
for c_in in new_cords:
if abs(c_out.x_start - c_in.x_start) < 3 or abs(c_out.x_end - c_in.x_end) < 3 or abs(c_out.y_start - c_in.y_start) < 3 or abs(c_out.y_end - c_in.y_end) < 3:
new_cords.remove(c_out)
但是我得到了例外,因为它删除了不存在的值并且我没有得到正确的列表。
我的算法有什么问题?
编辑:算法应该只删除其中之一。 例如,A 和 B 很接近,所以我们应该删除 A(或 B),但不能同时删除它们
我理解的任务是删除列表中的一些矩形,以便剩余的矩形不会太相似。
最大化剩下的矩形数量实际上是一个图论问题。
以下解决方案不是最优的,但可以使剩余数量尽可能大:
def remove_similar(cord_list):
is_similar = (
lambda n1, n2: abs(n1.x_start - n2.x_start) < 3
or abs(n1.x_end - n2.x_end) < 3
or abs(n1.y_start - n2.y_start) < 3
or abs(n1.y_end - n2.y_end) < 3
)
res = []
while cord_list:
c_in = cord_list.pop()
cord_list = [n for n in cord_list if not is_similar(n, c_in)]
res.append(c_in)
return res
为了确保代码有效,我对 100 个矩形的列表运行了 1000 次测试:
import numpy as np
def build_test(size):
return [cords(*np.random.randint(0, 1000, 4).tolist()) for _ in range(size)]
def check(cord_list):
assert not any(
[n1 != n2 and too_close(n1, n2) for n1 in cord_list for n2 in cord_list]
)
return len(cord_list)
res_size_mean = 0
for _ in range(1000):
new_cords = build_test(100)
res = remove_similar(new_cords)
res_size_mean += check(res) / 1000
print(res_size_mean)
# 53.591999999999736
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.