假设我的最大图片尺寸为
totalpixels = (45, 45)
我想通过
拆分此图片split_image = (10,20) #split the 45x45 pixels into 10x20 pixels
我可以得到的坐标列表是当我将45x45图像分割成10x20时
[(0,0), (10,0), (20,0), (30,0), (0,20), (10,20), (20,20), (30,20)]
因此,我从(0,0)坐标开始,从这里我添加
(0,0)
(10,0) = (10,0)
(10+10,0) = (20,0)
(20+10,0) = (30,0)
(0,0+20) = (0,20)
(0+10,20) = (10,20)
(10+10,20)= (20,20)
(20+10,20)= (30,20)
我假设我必须制作两个for循环,
for x in range(total[0]): #Is the range supposed to be this?
for y in range(total[1]):
#I'm not sure how to append values according to the split value
答案 0 :(得分:3)
for
循环不是必需的:
>>> [(x, y) for x in range(0, 31, 10) for y in range(0, 21, 20)]
[(0, 0), (0, 20), (10, 0), (10, 20), (20, 0), (20, 20), (30, 0), (30, 20)]
此列表推导会生成您指定的结果。
范围的参数是start,stop和step。您为x指定了10的步长值,为y指定了20的步长值。请注意range
在“停止”值(第二个参数)之前停止。因此,如果您希望最高“x”值为30,则需要使“停止”大于此值。
您似乎想要所有大小为split_image的像素块的边缘坐标,从(0,0)开始,适合但不超出,大小的图像totalpixels。计算它的一般函数是:
def coords(split_image, totalpixels):
xstop = totalpixels[0] - split_image[0]
ystop = totalpixels[1] - split_image[1]
return [(x, y) for x in range(0, xstop, split_image[0])
for y in range(0, ystop, split_image[1])]
在参数值上运行时,它会产生:
>>> coords( (10, 20), (45, 45) )
[(0, 0), (0, 20), (10, 0), (10, 20), (20, 0), (20, 20), (30, 0), (30, 20)]
答案 1 :(得分:1)
我认为你想使用带有步骤参数的范围:
range(start, stop[, step])
所以你可以这样做:
>>> result = []
>>> totalpixels = (45, 45)
>>> split_image = (10,20) #split the 45x45 pixels into 10x20 pixels
>>> for x in range(0, totalpixels[0], split_image[0]):
... for y in range(0, totalpixels[1], split_image[1]):
... result.append((x,y))
...
>>> result
[(0, 0), (0, 20), (0, 40), (10, 0), (10, 20), (10, 40), (20, 0), (20, 20), (20, 40), (30, 0), (30, 20), (30, 40), (40, 0), (40, 20), (40, 40)]
>>>
或者只是
>>> [(x, y) for x in range(0, totalpixels[0], split_image[0]) for y in range(0, totalpixels[1], split_image[1])]
[(0, 0), (0, 20), (0, 40), (10, 0), (10, 20), (10, 40), (20, 0), (20, 20), (20, 40), (30, 0), (30, 20), (30, 40), (40, 0), (40, 20), (40, 40)]
这会产生分割图像的坐标,如下所示:
0 10 20 30 40 45 +-----+-----+-----+-----+--+ | | | | | | | | | | | | 20 +-----+-----+-----+-----+--+ | | | | | | | | | | | | 40 +-----+-----+-----+-----+--+ | | | | | | 45 +-----+-----+-----+-----+--+
希望我能提供帮助。