我正试着在画布上粘贴3个矩形图像。目标是图像在画布内,并且它们不会重叠。为此,我决定生成3个二元组的值,它们将用作图像左上角的xy坐标的位置。如下所示:
locations_used = [(950, 916), (1097, 119), (1290, 526)]相反,它所做的是重复第一个值3x,然后添加两个新值,当我指定3时,总共得到5个位置。如下所示:
[(950, 916), (950, 916), (950, 916), (1097, 119), (1290, 526)]这是我的代码的MRE:
n = 3
canvas_width = 500
canvas_height = 300
logo_width = 50
logo_height = 30
locations_used = []
for i in range(0, n):
logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
locations_used.append((logo_location_x, logo_location_y))
for img in locations_used:
if logo_location_x in range(img[0], logo_width) or logo_location_y in range(img[1], logo_height):
pass
else:
while len(locations_used) < n:
locations_used.append((logo_location_x, logo_location_y))
print(len(locations_used))
print(locations_used)
print('\n')输出:
5
[(950, 916), (950, 916), (950, 916), (1097, 119), (1290, 526)]发布于 2021-01-28 12:49:51
在第一次迭代中,将logo_location_x(950)和logo_location_y(916)与range(950, 50)和range(916, 30)进行比较。由于start参数比stop小,所以range为空,程序继续执行else子句。当locations_used的长度小于3时,将添加相同的值,从而使数组成为[(950, 916), (950, 916), (950, 916]。
在接下来的两次迭代中,每个新的x, y对都会添加到locations_used中。当range(img[0], logo_width)和range(img[1], logo_height)仍然为空时,locations_used的长度大于n,因此不会添加额外的元素。
这是经过编辑的代码,用于创建n而不是重叠位置。
# Instead of iterating only 3 times, try until list is full.
while len(locations_used) < n:
logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
# Don't add position until it is checked that it doesn't overlap.
# locations_used.append((logo_location_x, logo_location_y))
# Check if new rectangle candidate overlaps with previous ones.
overlap = False
for img in locations_used:
# Fix range usage. I hope this is what you want.
if logo_location_x in range(img[0] - logo_width, img[0] + logo_width) and logo_location_y in range(img[1] - logo_height, img[1] + logo_height):
overlap = True
break
# Add position to list after you ensure that new position
if not overlap:
locations_used.append((logo_location_x, logo_location_y))发布于 2021-01-28 12:49:59
您的else语句没有正确缩进。尝尝这个
if logo_location_x in range(img[0], logo_width) or logo_location_y in range(img[1], logo_height):
pass
else:
while len(locations_used) < n:
locations_used.append((logo_location_x, logo_location_y))https://stackoverflow.com/questions/65931082
复制相似问题