在2D图像的每个图像像素中创建居中的面片



大家好,我正在尝试从2D图像创建补丁。我需要这些补丁必须集中在每个像素图像中。我使用的是这个代码:

#patches for each point in 2D slice
patch_size = 27
pacth_m_size = patch_size//2
for x in range(0, sld_arr_norm.shape[0]):
for y in range(0, sld_arr_norm.shape[1]):
if x-pacth_m_size>0: # if all is ok the get the patch
if y-pacth_m_size>0:
if x+pacth_m_size<sld_arr_norm.shape[1]:
if y+pacth_m_size<sld_arr_norm.shape[1]:
x_i = x-pacth_m_size
x_s = x+pacth_m_size+1
y_i = y-pacth_m_size
y_s = y+pacth_m_size+1
curr_patch= sld_arr_norm[x_i:x_s, y_i:y_s]
assert curr_patch.shape == (patch_size, patch_size)
print(curr_patch.shape)
else:
x_i = x-pacth_m_size
x_s = x+pacth_m_size+1
y_i = y-pacth_m_size
y_s = y+pacth_m_size+1
if x-pacth_m_size<0:
issue_patch = sld_arr_norm[0:x_s, y_i:y_s]
curr_patch  = np.zeros((patch_size, patch_size))
star_index  = abs(x-pacth_m_size)
curr_pacth[star_index:,:]=issue_patch.copy()
if y-pacth_m_size<0:
issue_patch = sld_arr_norm[x_i:x_s, 0:y_s]
curr_patch  = np.zeros((patch_size, patch_size))
star_index  = abs(y_i)
curr_pacth[:, star_index:]=issue_patch.copy()
if y+pacth_m_size>sld_arr_norm.shape[1]:
issue_patch = sld_arr_norm[x_i:x_s, y_i:y_s]
curr_patch  = np.zeros((patch_size, patch_size))
end_index   = abs(y_s-issue_patch.shape[1])
curr_patch[0:, 0:curr_patch.shape[1]-end_index]=issue_patch.copy() #issue_patch[x_i:x_s, y_i:issue_patch.shape[1]]
if x+pacth_m_size>sld_arr_norm.shape[0]:
issue_patch = sld_arr_norm[x_i:x_s, y_i:y_s]
curr_patch  = np.zeros((patch_size, patch_size)) 
end_index   = abs(x_s-issue_patch.shape[0])
curr_patch[0:arr_zeros.shape[0]-end_index, :]=issue_patch.copy()
assert curr_patch.shape == (patch_size, patch_size)
print(curr_patch.shape)

问题是在图像的边界上,我面临着一些问题,比如补丁不符合定义的补丁大小。你知道有哪个库允许用这种方式创建补丁吗?

最好的方法是首先填充整个图像。然后,我们可以在不担心边缘的情况下继续提取补丁。代码如下所示:

#Define patch size 
patch_size   = 13
pacth_m_size = patch_size//2
#Patch the whole image 
sld_arr_norm_pad = np.pad(sld_arr_norm, pacth_m_size, 'wrap')
for x in range(0, sld_arr_norm.shape[0]):
for y in range(0, sld_arr_norm.shape[1]):
x_real = x + pacth_m_size
y_real = y + pacth_m_size
x_i = x_real - pacth_m_size
x_s = x_real + pacth_m_size + 1
y_i = y_real - pacth_m_size
y_s = y_real + pacth_m_size + 1
curr_patch = sld_arr_norm_pad[x_i:x_s, y_i:y_s]
print(curr_patch.shape)
print((x_i, x_s, y_i, y_s))
assert curr_patch.shape == (patch_size, patch_size)

希望这能帮助其他人。

最新更新