【发布时间】:2018-06-06 15:29:37
【问题描述】:
我有一个 numpy 数组 I,它存储 N 大小为 P(像素数)的图像。每张图片的大小为P = q*q。
N = 1000 # number of images
q = 10 # length and width of image
P = q*q # pixels of image
I = np.ones((N,P)) # array with N images of size P
现在我想删除选定索引 IDX 周围大小为 ps 的补丁(将所有值设置为零)。
ps = 2 # patch size (ps x ps)
IDX = np.random.randint(0,P,(N,1))
我的方法是使用reshape(q,q) 重塑每个图像并删除IDX 周围的像素。这里我有一个问题,我不知道如何计算给定IDX 的图像内的位置。另外,我必须检查索引是否不在图像之外。
如何解决这个问题,有没有办法向量化这个过程?
编辑:
在@Brenlla 的帮助下,我执行了以下操作来删除补丁。我的方法的问题是,它需要三个 for 循环,而且我必须对每个图像进行两次重塑。有什么办法可以提高性能吗?这部分显着降低了我的代码速度。
import numpy as np
import matplotlib.pyplot as plt
def myplot(I):
imgs = 10
for i in range(imgs**2):
plt.subplot(imgs,imgs,(i+1))
plt.imshow(I[i].reshape(q,q), interpolation="none")
plt.axis("off")
plt.show()
N = 10000
q = 28
P = q*q
I = np.random.rand(N,P)
ps = 3
IDX = np.random.randint(0,P,(N,1))
for i in range(N):
img = I[i].reshape(q,q)
y0, x0 = np.unravel_index(IDX[i,0],(q,q))
for x in range(ps):
for y in range(ps):
if (x0+x < q) and (y0+y < q):
img[x0+x,y0+y] = 2.0
I[i] = img.reshape(1,q*q)
myplot(I)
【问题讨论】:
-
在寻找向量化方法之前,先研究一个循环解决方案?
-
我已经尝试过了,但是在给定 IDX 索引的情况下,我必须在图像中找到坐标 (x,y)。我也省略了这个问题,发现这样做需要很长时间。
-
要找到坐标(x,y),你可以
np.unravel_index(IDX, (q,q)) -
@Brenlla 太棒了!我不知道。我会尝试并更新我的问题。
标签: python performance numpy vectorization