我正在使用图片列表 image_list 。 image_list 中的每个项目都是一个形状为(X,Y,3)的numpy数组。 X是高度,Y是宽度,每个图像有3种颜色通道。
我想获得所有图像的最大宽度和高度,并调整每个图像的大小,使得如果有额外的空间,则底部和右侧填充0。我可以做第一部分(获得最大高度和最大宽度),但我正在努力与第二部分(调整和填充右侧和底部的多余区域用零)。
max_height = 0
max_width = 0
for image in image_list:
shape = image.shape
if shape[0] > max_height:
max_height = shape[0]
if shape[1] > max_width:
max_width = shape[1]
为了调整大小,我尝试过:
image.resize((max_height, max_width, 3))
但这有时只会起作用。其他时候你会重复多次重复相同的图像。
答案 0 :(得分:1)
方法#1
这是一种方法,A
是图像的输入列表 -
M,N = np.max([i.shape[:2] for i in A],0)
M_ext = [M-i.shape[0] for i in A]
N_ext = [N-i.shape[1] for i in A]
out = [img3D_pad(a,M_ext[i],N_ext[i]) for i,a in enumerate(A)]
辅助功能 -
def img3D_pad(a,m,n):
return np.pad(a,((0,m),(0,n),(0,0)),'constant')
<强>验证强>
1)形状验证:
In [108]: A = [np.random.randint(11,99,(4,5,3)), np.random.randint(11,99,(2,6,3))]
In [109]: [i.shape for i in out]
Out[109]: [(4, 6, 3), (4, 6, 3)]
2)价值验证:
In [110]: A[0][...,0]
Out[110]:
array([[53, 64, 41, 13, 85],
[74, 53, 88, 47, 54],
[35, 26, 93, 68, 80],
[38, 68, 50, 83, 77]])
In [111]: out[0][...,0]
Out[111]:
array([[79, 33, 41, 16, 76, 0],
[11, 49, 54, 56, 40, 0],
[38, 43, 98, 95, 23, 0],
[26, 26, 20, 59, 53, 0]])
In [112]: A[1][...,0]
Out[112]:
array([[76, 44, 29, 20, 91, 71],
[71, 90, 11, 51, 81, 22]])
In [113]: out[1][...,0]
Out[113]:
array([[57, 11, 42, 95, 87, 75],
[15, 70, 88, 88, 41, 95],
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0]])
方法#2
基于zeros-initialization
-
M,N = np.max([i.shape[:2] for i in A],0)
out = [img3D_create(a,M,N) for i,a in enumerate(A)]
辅助功能 -
def img3D_create(a,M,N):
p,q,r = a.shape
out = np.zeros((M,N,r),dtype=a.dtype)
out[:p,:q] = a
return out