【发布时间】:2018-12-11 09:34:39
【问题描述】:
嗨)我正在尝试使用循环到 NumPy 操作来重构我的代码,以使代码更快。任何线索如何做到这一点?此代码根据 2D ndarray 中相邻元素的值为每个元素分配一个值,我找不到此类特定人员的任何答案。
这是在此处描述的照片上查找鞍点的 6 个邻居方法的实现https://documentcloud.adobe.com/link/track?uri=urn:aaid:scds:US:978c30d2-4888-491c-85c1-3949ea6166e9
它获取当前元素与其相邻元素的差异。然后它计算这些差异的符号变化,如果它> = 4,那么它就是鞍点。
没有循环就可以吗?
抱歉,如果问题不清楚或格式不正确 - 这是我在 StackOverflow 上发布的第一个问题
def findSaddlePoints6neibours(gray):
gray = gray.astype(int)
h = gray.shape[0]
w = gray.shape[1]
number = 0
result = np.zeros((h, w))
for y in range(1, h - 1):
for x in range(1, w - 1):
center = gray[y][x]
neiboursDiff = []
neiboursDiff.append(gray[y-1][x] - center)
neiboursDiff.append(gray[y-1][x+1] - center)
neiboursDiff.append(gray[y][x+1] - center)
neiboursDiff.append(gray[y+1][x] - center)
neiboursDiff.append(gray[y+1][x-1] - center)
neiboursDiff.append(gray[y][x-1] - center)
changes = 0
for i in range(5):
if (neiboursDiff[i] < 0 and neiboursDiff[i+1] > 0) or (neiboursDiff[i] > 0 and neiboursDiff[i+1] < 0):
changes += 1
if (neiboursDiff[0] < 0 and neiboursDiff[5] > 0) or (neiboursDiff[0] > 0 and neiboursDiff[5] < 0):
changes += 1
if changes > 3:
number += 1
result[y][x] = 1
return [result, number]
【问题讨论】:
-
您能否提供一些示例输入数据和一些预期输出?
标签: python numpy multidimensional-array