python - 从 ndarrys 的 ndarray 中删除元素

标签 python numpy

我有一个 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

的 466 x 700 ndarray

我想从 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/

相关文章:

python - Django 子进程从批处理脚本实时/无缓冲地报告标准输出

python - 使用 Pandas 读取包含一些缺失值的 CSV

python - 在python中读取预处理的cr2 RAW图像数据

python - 用其他数组切片 numpy 数组

python - 数据 View 不显示 DataFrame 的索引,也不显示 numpy 数组中的行号

python - 预期出现缩进 block 错误,我做错了什么

python - Django环境下如何执行外部脚本

Python Scrapy 并不总是从网站下载数据

pandas - Seaborn:如何在绘图 X 轴中的每个值后面添加 "%"符号,而不是将值转换为百分比?

python - 如何将numpy数组中的相同元素移动到子数组中