【发布时间】:2019-11-22 11:57:21
【问题描述】:
我有一个 256x256 数组,我想使用特殊的行和列向右移动。我正在使用 numpy.roll 来实现它。如果我使用以下代码,则 shift 是向右一列。
import cv2
import matplotlib.pyplot as plt
import numpy as np
# Input (256x256 0 values array)
array = np.zeros((256,256))
# Draw a square inside the array (1 values)
array[100:156,100:156] = 1
# Shift the square to the right (1 as shift value)
shifted_array = np.roll(array,1)
如果我无限重复该过程,它会在数组的整个宽度(256 列)上移动,然后重新启动。我想要做的是将数组从第 120 列移到第 130 列。这意味着最大移位是 10 列(而不是像以前那样的 256 列)。我怎样才能做到这一点?
[已解决] 最后,我找到了一种使用以下代码实现此目的的方法:
import cv2
import matplotlib.pyplot as plt
import numpy as np
# Input (256x256 0 values array)
array = np.zeros((256,256))
# Draw a square inside the array (1 values)
array[100:156,100:156] = 1
# Cropping the image between columns 120 and 130
cropped_image = array[:,120:130]
# Loop to shift the image every column and get the original dimensions
i = 1
shift_value = 1
while i < len(cropped_image):
shifted_array = np.roll(cropped_image, shift_value)
shift_value = shift_value + 1
i = i + 1
new_array = np.zeros(array.shape)
new_array[:,120:130] = shifted_array
【问题讨论】:
-
np.roll(array, 10)你在找什么? -
请提供minimal reproducible example 一些示例输入和示例输出。
-
你好奥斯巴克。感谢您的回复。不是真的因为我想保留 1 作为移位值并在数组的特殊列中进行移位。但无论如何,我想我找到了一种方法来实现这一点:(i)隔离新数组中的列,(ii)然后用新数组裁剪旧数组,(iii)移位,以及(iv)通过用 0 值填充新的移位数组。
-
@rdmato33 如果您自己解决了这个问题,请将其作为答案提供并接受,这样问题就解决了。它将帮助可能遇到相同问题的其他人。