【发布时间】:2018-11-29 16:10:57
【问题描述】:
我的二进制图像大小为256x256x256,其中前景区域位于一个小区域中,并且我有很多零边距。我想通过找到图像中像素非零的点的最小和最大坐标来切割零边缘。它奏效了,但它很耗时。我发布了我的代码,你能告诉我如何让它更快吗?
对于256x256x256的图片大小,大约需要0.13024640083312988秒。这是代码,你可以在线运行https://repl.it/repls/AnxiousExoticBackup
import numpy as np
import time
def cut_edge(image, keep_margin):
'''
function that cuts zero edge
'''
D, H, W = image.shape
D_s, D_e = 0, D - 1
H_s, H_e = 0, H - 1
W_s, W_e = 0, W - 1
while D_s < D:
if image[D_s].sum() != 0:
break
D_s += 1
while D_e > D_s:
if image[D_e].sum() != 0:
break
D_e -= 1
while H_s < H:
if image[:, H_s].sum() != 0:
break
H_s += 1
while H_e > H_s:
if image[:, H_e].sum() != 0:
break
H_e -= 1
while W_s < W:
if image[:, :, W_s].sum() != 0:
break
W_s += 1
while W_e > W_s:
if image[:, :, W_e].sum() != 0:
break
W_e -= 1
if keep_margin != 0:
D_s = max(0, D_s - keep_margin)
D_e = min(D - 1, D_e + keep_margin)
H_s = max(0, H_s - keep_margin)
H_e = min(H - 1, H_e + keep_margin)
W_s = max(0, W_s - keep_margin)
W_e = min(W - 1, W_e + keep_margin)
return int(D_s), int(D_e)+1, int(H_s), int(H_e)+1, int(W_s), int(W_e)+1
image = np.zeros ((256,256,256),dtype=np.float32)
ones_D_min, ones_D_max, ones_H_min, ones_H_max,ones_W_min, ones_W_max= 100,200, 90,150, 60,200
image[ones_D_min: ones_D_max,ones_H_min:ones_H_max, ones_W_min:ones_W_max]=1
t0=time.time()
ones_D_min_result, ones_D_max_result, ones_H_min_result, ones_H_max_result, ones_W_min_result, ones_W_max_result= cut_edge(image,0)
t1=time.time()
print ('Time consuming ', t1-t0)
print (ones_D_min, ones_D_max, ones_H_min, ones_H_max,ones_W_min, ones_W_max)
print (ones_D_min_result, ones_D_max_result, ones_H_min_result, ones_H_max_result, ones_W_min_result, ones_W_max_result)
【问题讨论】:
标签: arrays python-3.x numpy image-processing