Python 如何将多个图像填充到包含所有图像的最小形状?
我正在尝试编写一个函数来加载和处理NN的数据。 作为输入,我有一组不同大小的图片。图片应表示为带有RGB通道的3D numpy阵列。我需要它们的大小相同(最大图片的大小) 我试过Python 如何将多个图像填充到包含所有图像的最小形状?,python,numpy,multidimensional-array,Python,Numpy,Multidimensional Array,我正在尝试编写一个函数来加载和处理NN的数据。 作为输入,我有一组不同大小的图片。图片应表示为带有RGB通道的3D numpy阵列。我需要它们的大小相同(最大图片的大小) 我试过np.pad,但似乎我不知道它应该如何工作。事实上,即使我有填充物,我也不知道如何根据图片的大小来改变它。代码如下: 从PIL导入图像 将numpy作为np导入 进口cv2 导入操作系统 def加载_数据(路径): 氨基酸=['Ala'、'Arg'、'Asn'、'Asp'、'Cys'、'Gln'、'Glu'、'Gly'、
np.pad
,但似乎我不知道它应该如何工作。事实上,即使我有填充物,我也不知道如何根据图片的大小来改变它。代码如下:
从PIL导入图像
将numpy作为np导入
进口cv2
导入操作系统
def加载_数据(路径):
氨基酸=['Ala'、'Arg'、'Asn'、'Asp'、'Cys'、'Gln'、'Glu'、'Gly'、'His'、'Ile'、'Ini'、'Leu'、'Lys'、'Met'、'Phe'、'Pro'、'Pyr'、'Sec'、'Ser'、'Thr'、'Trp'、'Tyr'、'Val']
矩阵=[]
答案_标签=[]
name=os.listdir(路径)
以我的名义:
矩阵=cv2.imread(路径+i,1)
矩阵=np.pad(矩阵,(0,1),‘常数’,常数值=[255255])
对于氨基酸中的y:
如果i中的y+“-”:
a=[矩阵,y]
答案加上标签。附加(a)
返回带标签的答案
数据处理=加载数据(“/content/drive/My drive/Thesis/dl/img/ans/”)
我得到了这个错误:
ValueErrorTraceback (most recent call last)
<ipython-input-50-e021738e59ea> in <module>()
20 return answer_labeled
21
---> 22 data_processed = load_data("/content/drive/My Drive/Thesis/dl/img/ans/")
23
24 # print(len(os.listdir("/content/drive/My Drive/Thesis/dl/img/ans/")))
<ipython-input-50-e021738e59ea> in load_data(path)
13 for i in names:
14 matrix = cv2.imread(path + i, 1)
---> 15 matrix = np.pad(matrix, (0, 1), 'constant', constant_values=[255,255,255])
16 for y in aminoacids:
17 if y + "-" in i:
/usr/local/lib/python2.7/dist-packages/numpy/lib/arraypad.pyc in pad(array, pad_width, mode, **kwargs)
1208 kwargs[i] = _as_pairs(kwargs[i], narray.ndim, as_index=True)
1209 if i in ['end_values', 'constant_values']:
-> 1210 kwargs[i] = _as_pairs(kwargs[i], narray.ndim)
1211 else:
1212 # Drop back to old, slower np.apply_along_axis mode for user-supplied
/usr/local/lib/python2.7/dist-packages/numpy/lib/arraypad.pyc in _as_pairs(x, ndim, as_index)
951 # Converting the array with `tolist` seems to improve performance
952 # when iterating and indexing the result (see usage in `pad`)
--> 953 return np.broadcast_to(x, (ndim, 2)).tolist()
954
955
/usr/local/lib/python2.7/dist-packages/numpy/lib/stride_tricks.pyc in broadcast_to(array, shape, subok)
180 [1, 2, 3]])
181 """
--> 182 return _broadcast_to(array, shape, subok=subok, readonly=True)
183
184
/usr/local/lib/python2.7/dist-packages/numpy/lib/stride_tricks.pyc in _broadcast_to(array, shape, subok, readonly)
127 it = np.nditer(
128 (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
--> 129 op_flags=[op_flag], itershape=shape, order='C')
130 with it:
131 # never really has writebackifcopy semantics
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,) and requested shape (3,2)
ValueErrorTraceback(最近一次调用上次)
在()
20返回已标记的答案
21
--->22数据处理=加载数据(“/content/drive/My drive/Thesis/dl/img/ans/”)
23
24#打印(len(os.listdir(“/content/drive/My drive/Thesis/dl/img/ans/”))
加载_数据中(路径)
13我的名字:
14矩阵=cv2.imread(路径+i,1)
--->15矩阵=np.pad(矩阵,(0,1),‘常数’,常数值=[255255])
16对于氨基酸中的y:
17如果i中的y+“-”:
/pad中的usr/local/lib/python2.7/dist-packages/numpy/lib/arraypad.pyc(数组、pad_宽度、模式,**kwargs)
1208 kwargs[i]=_as_pairs(kwargs[i],narray.ndim,as_index=True)
1209如果i在['end_values','constant_values']中:
->1210 kwargs[i]=_as_pairs(kwargs[i],narray.ndim)
1211其他:
1212#返回到旧的、较慢的np。对于用户提供的,沿_轴应用_模式
/usr/local/lib/python2.7/dist-packages/numpy/lib/arraypad.pyc成对(x,ndim,as_索引)
951#使用“tolist”转换数组似乎可以提高性能
952#对结果进行迭代和索引时(请参见“pad”中的用法)
-->953将np.broadcast_返回(x,(ndim,2)).tolist()
954
955
/广播中的usr/local/lib/python2.7/dist-packages/numpy/lib/stride_tricks.pyc(数组、形状、子对象)
180 [1, 2, 3]])
181 """
-->182返回到(数组、形状、subok=subok、readonly=True)
183
184
/usr/local/lib/python2.7/dist-packages/numpy/lib/stride\u tricks.pyc in\u broadcast\u to(数组、形状、子对象、只读)
127 it=np.nditer(
128(数组,),标志=['multi_index'、'refs_ok'、'zerosize_ok']+附加,
-->129 op_标志=[op_标志],itershape=形状,顺序='C')
130有了它:
131#从来没有真正的writebackifcopy语义
ValueError:操作数无法与重新映射的形状[原始->重新映射]:(3,)和请求的形状(3,2)一起广播
当然,我试着用谷歌搜索这个错误,但没有找到对我有用或可以理解的东西(因为我对编程非常陌生)。我非常感谢任何帮助和想法。使用np.pad()
实际上非常好
使用您提供的数字处理三维数据的示例如下:
import numpy as np
arr = np.random.randint(0, 255, (72, 72, 3))
new_arr = np.pad(
arr, ((0, 92 - 72), (0, 92 - 72), (0, 0)),
'constant', constant_values=255)
print(new_arr.shape)
# (92, 92, 3)
编辑 要解决完整的问题,首先需要确定最大尺寸,然后相应地填充所有其他图像。 该软件包为您提供了许多功能,可以更轻松地完成工作(免责声明:我是它的主要作者)
如果您可以将所有图像存储在内存中,最简单的方法就是使用,即:
如果无法将所有数据放入内存,则应分两次进行,一次是计算适合所有输入的最小形状,然后使用以下方法执行实际填充:
在内部,
fc.extra.reframe()
正在使用np.pad()
(或类似的东西,但速度更快),大致相当于:
def reframe(arr, target_shape, position=0.5, *args, **kws):
source_shape = arr.shape
padding = tuple(
(int(position * (dim_target - dim_source)),
(dim_target - dim_source) - int(position * (dim_target - dim_source)))
for dim_target, dim_source in zip(target_shape, source_shape))
return np.pad(arr, padding, *args, **kws)
reframe(arr, target_shape, 0.5, 'constant', constant_values=255)
请注意,position
参数确定数组相对于新形状的放置位置。0.5
的默认值将使所有图像放置在中心,而0.0
或1.0
将其推到所有轴上新形状的一侧或另一侧。
FlyingCircus版本更灵活,因为您可以分别为所有轴指定一个
位置值。我曾经不得不解决一个类似的任务,因此我为它创建了以下函数。它允许为每个维度指定大小差异的分数,该分数应该在前后填充(类似于np.pad
)。例如,如果您有两个形状数组(3,)
和(5,)
,那么before=1
将填充整个差异(在本例中为2
)在左侧,而before=0.5
在左侧和右侧分别填充一个元素。与np类似,pad
也可以为每个维度指定这些因子。以下是实现:
import numpy as np
def pad_max_shape(arrays, before=None, after=1, value=0, tie_break=np.floor):
"""Pad the given arrays with a constant values such that their new shapes fit the biggest array.
Parameters
----------
arrays : sequence of arrays of the same rank
before, after : {float, sequence, array_like}
Similar to `np.pad -> pad_width` but specifies the fraction of values to be padded before
and after respectively for each of the arrays. Must be between 0 and 1.
If `before` is given then `after` is ignored.
value : scalar
The pad value.
tie_break : ufunc
The actual number of items to be padded _before_ is computed as the total number of elements
to be padded times the `before` fraction and the actual number of items to be padded _after_
is the remainder. This function determines how the fractional part of the `before` pad width
is treated. The actual `before` pad with is computed as ``tie_break(N * before).astype(int)``
where ``N`` is the total pad width. By default `tie_break` just takes the `np.floor` (i.e.
attributing the fraction part to the `after` pad width). The after pad width is computed as
``total_pad_width - before_pad_width``.
Returns
-------
padded_arrays : list of arrays
Notes
-----
By default the `before` pad width is computed as the floor of the `before` fraction times the number
of missing items for each axis. This is done regardless of whether `before` or `after` is provided
as a function input. For that reason the fractional part of the `before` pad width is attributed
to the `after` pad width (e.g. if the total pad width is 3 and the left fraction is 0.5 then the
`before` pad width is 1 and the `after` pad width is 2; in order to f). This behavior can be controlled
with the `tie_break` parameter.
"""
shapes = np.array([x.shape for x in arrays])
if before is not None:
before = np.zeros_like(shapes) + before
else:
before = np.ones_like(shapes) - after
max_size = shapes.max(axis=0, keepdims=True)
margin = (max_size - shapes)
pad_before = tie_break(margin * before.astype(float)).astype(int)
pad_after = margin - pad_before
pad = np.stack([pad_before, pad_after], axis=2)
return [np.pad(x, w, mode='constant', constant_values=value) for x, w in zip(arrays, pad)]
例如,您可以按如下方式使用它:
test = [np.ones(shape=(i, i, 3)) for i in range(5, 10)]
result = pad_max_shape(test, before=0.5, value=255)
print([x.shape for x in result])
print(result[0][:, :, 0])
这将产生以下输出:
[(9, 9, 3), (9, 9, 3), (9, 9, 3), (9, 9, 3), (9, 9, 3)]
[[255. 255. 255. 255. 255. 255. 255. 255. 255.]
[255. 255. 255. 255. 255. 255. 255. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 255. 255. 255. 255. 255. 255. 255.]
[255. 255. 255. 255. 255. 255. 255. 255. 255.]]
因此,我们可以看到,每个数组都被对称地填充到最大数组的形状(9,9,3)
错误似乎不完整,或者与您发布的代码相关。它是完整的和相关的,我编辑了文章(使用函数时出现错误)@LisaGrigorashvili不,它不完整。细节隐藏在4帧中
。你应该能够单击那里并获得完整的跟踪。这就是MadPhysicator的评论所指的。给定
test = [np.ones(shape=(i, i, 3)) for i in range(5, 10)]
result = pad_max_shape(test, before=0.5, value=255)
print([x.shape for x in result])
print(result[0][:, :, 0])
[(9, 9, 3), (9, 9, 3), (9, 9, 3), (9, 9, 3), (9, 9, 3)]
[[255. 255. 255. 255. 255. 255. 255. 255. 255.]
[255. 255. 255. 255. 255. 255. 255. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 1. 1. 1. 1. 1. 255. 255.]
[255. 255. 255. 255. 255. 255. 255. 255. 255.]
[255. 255. 255. 255. 255. 255. 255. 255. 255.]]