Python 如何向量化这个执行图像内子矩形分配的循环

问题描述 投票:0回答:1

我有 2 个数组:

bot
top
,以及一个
image
。我需要循环遍历数组,对于每对
(bot,top)
,我需要用255填充从行
3 * i + 1
bot[i]
的列
top[i]

我想使用矢量化代码而不是 for 循环以使其更快。我尝试过一些数组索引,但我不知道正确的语法。

我应该如何更改下面的代码?

import numpy as np
import pandas as pd

N = 100
image = np.zeros((32, 32))

np.random.seed(42)

data = {
    'Bot': np.array([2, 5, 3, 1, 7], dtype=np.int32),
    'Top': np.array([3, 6, 4, 2, 10], dtype=np.int32)
}

# I don't have access to data, just df
df = pd.DataFrame(data)

value = 255
for i in range(len(data)):
    image[df.loc[i]['Bot'] : df.loc[i]['Top'] + 1, 3 * i + 1] = value

image2 = np.zeros((32, 32))
image2[df['Bot'] : df['Top'] + 1, np.arange(len(df)) * 3 + 1] = value # error on this line

print(image == image2)

运行上面的代码,出现此错误

ERROR!
Traceback (most recent call last):
  File "<string>", line 24, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
python pandas numpy optimization vectorization
1个回答
0
投票

关于:

import numpy as np

image = np.zeros((32, 32))

bot = np.array([2, 5, 3, 1, 7], dtype=np.int32),
top = np.array([3, 6, 4, 2, 10], dtype=np.int32)

value = 255

top2 = 3 * top + 1
dim1 = [list(range(z[0], z[1])) for z in zip(top, top2)]
repeat = [len(itm) for itm in dim1]
dim1 = [itm for sublist in dim1 for itm in sublist]
dim0 = np.repeat(bot, repeat)
image[dim0, dim1] = value

我对分度精度不是100%。您可能需要在某个地方添加 -1/+1。

© www.soinside.com 2019 - 2024. All rights reserved.