我试图迭代源数组以更改目标数组中的一些元素,但是我无法获得正确的索引,我的偏移量无法理解。通常,我的任务是在条件允许的情况下更改元素
import numpy as np
x = np.linspace(0,1000, 1000/50)
y = np.linspace(0,1000, 1000/50)
X,Y = np.meshgrid(x,y)
source = np.column_stack([X.ravel(), Y.ravel()]).astype(int)
destination = source.copy()
for x, i in np.ndenumerate(source):
# if smth:
destination[i] = np.array([x[0] + 10, x[1]])
我想我不应该使用源数组,而应该遍历目标数组(这不能使用标准方法完成),请提前告诉我正确的解决方案。
Current output:
[421 789]
[473 789]
[526 789]
[578 789]
[631 789]
[684 789]
Required output:
[431 789]
[483 789]
[536 789]
[588 789]
[641 789]
[694 789]
我将更简单地解释一下,我有一个网格,它有一些点,我需要将这些点向右移动,例如88、89、90、10像素,为此,我需要一个源和目标数组(其中这些点是偏移的),枚举很可能不适合我,但是通常在目标中对数组进行编辑,例如x:当编辑x给出所需的结果时,但这不适用于ndarray
for x, i in enumerate(destination):
inside = cv2.pointPolygonTest(cnt, (destination[x,0],
destination[x,1]), False)
if inside > 0:
cv2.circle(img, (destination[x,0], destination[x,1]), 10,
(255,0,0), 2)
destination[x] = np.array([destination[x,0] + 10, destination[x,1]])
# Contour(cnt)
[[550 42]
[600 42]
[690 273]
[640 273]]
如您所知,我需要将蓝色圆圈上的所有内容移动10像素
从数据创建到目标区域修改,我们可以将其分为三个步骤。可以numpy
通过numpy.where
和和numpy.logical_and
(如果需要)使用索引以及条件区域选择来实现修改。
import numpy as np
x = np.linspace(0,1000, int(1000/50))
y = np.linspace(0,1000, int(1000/50))
X,Y = np.meshgrid(x,y)
source = np.column_stack([X.ravel(), Y.ravel()]).astype(int)
destination = source.copy()
target_index = np.where(np.logical_and(destination[:,1]==789, destination[:,0]>=421))
destination[target_index]
输出:
array([[ 421, 789],
[ 473, 789],
[ 526, 789],
[ 578, 789],
[ 631, 789],
[ 684, 789],
[ 736, 789],
[ 789, 789],
[ 842, 789],
[ 894, 789],
[ 947, 789],
[1000, 789]])
3.更改目标区域
scope = destination[target_index]
scope[:,0] = scope[:,0] + 10
destination[target_index] = scope
destination[target_index]
输出:
array([[ 431, 789],
[ 483, 789],
[ 536, 789],
[ 588, 789],
[ 641, 789],
[ 694, 789],
[ 746, 789],
[ 799, 789],
[ 852, 789],
[ 904, 789],
[ 957, 789],
[1010, 789]])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句