我有一个 466 x 700 numpy.ndarry
。对于 466 x 700 ndarray
中的每个 ndarray
,我想按索引删除一个元素。到目前为止是这样的:
normalized_img = numpy.atleast_3d(img).astype(numpy.float) / 255.
for x, y in seam:
numpy.delete(normalized_img[y], x)
seam
由坐标元组 (x, y)
和
img
是一个带有 dtype=uint8
我想从 normalized_img
中删除 (x, y)
。我该怎么做?使用 pdb.set_trace()
,我可以看到它仍然是 466 x 700,即使在我遍历所有 seam
之后也是如此。 seam
的长度为 466。在遍历所有 seam
后,我期望 466 x 699。
接缝
示例:(13,0), (12,1), (11,2), (10,3), ...
等
我也试过:
normalized_img = numpy.atleast_3d(img).astype(numpy.float) / 255.
for x, y in seam:
normalized_img[y] = numpy.delete(normalized_img[y], x)
但是我得到这个错误:
Traceback (most recent call last):
File "seam_carver.py", line 118, in <module>
sys.exit(main(sys.argv))
File "seam_carver.py", line 114, in main
sc = SeamCarver(image, int(width), int(height))
File "seam_carver.py", line 29, in __init__
self.seam_carve()
File "seam_carver.py", line 79, in seam_carve
normalized_img[y] = numpy.delete(normalized_img[y], x)
ValueError: could not broadcast input array from shape (2099) into shape (700,3)
我认为这是由于形状不匹配造成的,但我不确定如何解决这个问题。
最佳答案
我无法轻易重现您的问题,但 documentation声明 numpy.delete 返回:
A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.
这意味着您的更改不会应用到数组本身,而是应用到它的副本,并且需要额外的步骤来修改 normalized_img
。
这假设您要将每一行修剪一列(如果最终数组大小应该少一列,这就是您期望的结果?)
tr_sz =(normalized_img.shape[0],normalized_img.shape[1]-1)
temp = np.zeros(tr_sz)
for x, y in seam:
temp[y] = np.delete(normalized_img[y], x)
normalized_img = temp
关于python - 从 ndarrys 的 ndarray 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46615814/