[英]How to change 2D array elements in Numpy?
我正在尝试迭代源数组以更改目标数组中的一些元素,但我无法获得正确的索引,我有难以理解的偏移量。 一般来说,我的任务是在条件需要时更改元素
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 个像素,为此我需要一个源和目标数组(其中这些点是偏移的),枚举很可能它不适合我,但通常编辑像 for x indestination 的数组:当编辑 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 个像素
你问什么根本不清楚。 你想怎么修改destination
?
另外,您确定需要np.ndenumerate
而不是enumerate
吗?
这是一种根据sources
中的值修改它的方法。 在 position (index) x
,目标将等于source
+ 10 的第一列的x
元素并等于source
第二列的x
元素。
for index, value in enumerate(source):
destination[index] = [source[index,0]+10, source[index,1]] # x+10, y same
从数据创建到目标区域修改,我们可以将其分为三个步骤。 可以使用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]
Output :
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]
Output :
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.