【发布时间】:2012-12-01 05:17:10
【问题描述】:
假设我有一个大小为 100x100 的矩阵,我想将每个像素与其直接邻居(左、上、右、下)进行比较,然后对当前矩阵或相同大小的新矩阵进行一些操作。 Python/Numpy 中的示例代码如下所示: (比较>0.5没有意义,我只是想在比较邻居时给出一些操作的工作示例)
import numpy as np
my_matrix = np.random.rand(100,100)
new_matrix = np.array((100,100))
my_range = np.arange(1,99)
for i in my_range:
for j in my_range:
if my_matrix[i,j+1] > 0.5:
new_matrix[i,j+1] = 1
if my_matrix[i,j-1] > 0.5:
new_matrix[i,j-1] = 1
if my_matrix[i+1,j] > 0.5:
new_matrix[i+1,j] = 1
if my_matrix[i-1,j] > 0.5:
new_matrix[i-1,j] = 1
if my_matrix[i+1,j+1] > 0.5:
new_matrix[i+1,j+1] = 1
if my_matrix[i+1,j-1] > 0.5:
new_matrix[i+1,j-1] = 1
if my_matrix[i-1,j+1] > 0.5:
new_matrix[i-1,j+1] = 1
如果我想进入一个相邻的单元格并从它开始与它的邻居进行比较,这可能会变得非常讨厌......您有什么建议可以如何以更有效的方式完成吗?这甚至可能吗?
【问题讨论】:
-
也许你应该澄清你想要什么......只是猜测,看起来你想知道哪个值为 1 的像素被 8 个像素包围,所有像素都是 1。是这样吗?
标签: python matlab matrix numpy scipy