【问题标题】:Remove pixels in image which is stored as array删除存储为数组的图像中的像素
【发布时间】: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


【解决方案1】:

是的,可以这样做,但需要大量使用np.broadcasting

生成数据以及I 的硬拷贝:

import time

N = 10000
q = 28
P = q*q
ps = 3 
I = np.random.rand(N,P)
IDX = np.random.randint(0,P,(N,1))
I_copy = I.copy()

现在运行循环解决方案。我切换了x0y0

t0=time.clock()
for i in range(N):
    img = I[i].reshape(q,q)
    x0, y0 = 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)
print('With loop: {:.2f} ms'.format(time.clock()*1e3-t0*1e3))

大约。在我的机器上为 276 毫秒。现在广播:

t0 = time.clock()
x_shift, y_shift = np.meshgrid(range(ps), range(ps))
x, y = np.unravel_index(IDX, (q,q))
#roi for region of interest
roix = x[:,:,None]+x_shift; 
roiy = y[:,:,None]+y_shift;
roix[roix>q-1] = q-1; roiy[roiy>q-1] = q-1;
I_copy.reshape(N,q,q)[np.arange(N)[:, None, None], roix, roiy] = 2.0

print('No loop: {:.2f} ms'.format(time.clock()*1e3-t0*1e3))

print(np.array_equal(I, I_copy))

大约快 80 倍

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多