【发布时间】:2018-10-06 03:52:31
【问题描述】:
我有一个细分项目。我有图像和标签,其中包含分割的基本事实。图像很大,并且包含很多“空白”区域。 我想从图像和标签中剪切补丁,以便补丁中包含非零标签。
我需要它尽可能高效。
我写了下面的代码,但是速度很慢。任何改进都将受到高度赞赏。
import numpy as np
import matplotlib.pyplot as plt
让我们创建虚拟数据
img = np.random.rand(300,200,3)
img[240:250,120:200]=0
mask = np.zeros((300,200))
mask[220:260,120:300]=0.7
mask[250:270,140:170]=0.3
f, axarr = plt.subplots(1,2, figsize = (10, 5))
axarr[0].imshow(img)
axarr[1].imshow(mask)[![enter image description here][1]][1]
plt.show()
我的低效代码:
IM_SIZE = 60 # Patch size
x_min, y_min = 0,0
x_max = img.shape[0] - IM_SIZE
y_max = img.shape[1] - IM_SIZE
xd, yd, x, y = 0,0,0,0
if (mask.max() > 0):
xd, yd = np.where(mask>0)
x_min = xd.min()
y_min = yd.min()
x_max = min(xd.max()- IM_SIZE-1, img.shape[0] - IM_SIZE-1)
y_max = min(yd.max()- IM_SIZE-1, img.shape[1] - IM_SIZE-1)
if (y_min >= y_max):
y = y_max
if (y + IM_SIZE >= img.shape[1] ):
print('Error')
else:
y = np.random.randint(y_min,y_max)
if (x_min>=x_max):
x = x_max
if (x+IM_SIZE >= img.shape[0] ):
print('Error')
else:
x = np.random.randint(x_min,x_max )
print(x,y)
img = img[x:x+IM_SIZE, y:y+IM_SIZE,:]
mask = mask[x:x+IM_SIZE, y:y+IM_SIZE]
f, axarr = plt.subplots(1,2, figsize = (10, 5))
axarr[0].imshow(img)
axarr[1].imshow(mask)
plt.show()
【问题讨论】:
标签: python performance numpy processing-efficiency