Python 如何在矩阵中找到所有相邻值对?
对于表示为矩阵的图像,什么是查找3x3正方形内接触的所有唯一元素对的有效方法Python 如何在矩阵中找到所有相邻值对?,python,image-processing,matrix,Python,Image Processing,Matrix,对于表示为矩阵的图像,什么是查找3x3正方形内接触的所有唯一元素对的有效方法 Let A= 1 1 2 2 3 3 3 1 1 1 1 2 4 4 1 1 2 2 5 5 5 然后我们会回来 (1,2),(1,3),(1,5),(2,3),(2,4),(2,5),(3,4),(4,5) 您可以使用来实现这一点。下面是示例代码: a = [[1, 1, 2, 2, 3, 3, 3,], [1, 1, 1, 1, 2, 4, 4,], [1, 1, 2
Let A=
1 1 2 2 3 3 3
1 1 1 1 2 4 4
1 1 2 2 5 5 5
然后我们会回来
(1,2),(1,3),(1,5),(2,3),(2,4),(2,5),(3,4),(4,5)
您可以使用来实现这一点。下面是示例代码:
a = [[1, 1, 2, 2, 3, 3, 3,],
[1, 1, 1, 1, 2, 4, 4,],
[1, 1, 2, 2, 5, 5, 5,],
]
# Extract boundry values to list
boundary_vals = a[0] + a[-1] + [sub_list[0] for sub_list in a[1:-1]] + [sub_list[-1] for sub_list in a[1:-1]]
# Unique set of values
unique_vals = set(boundary_vals)
# Calculate combinations
from itertools import combinations
my_values = list(combinations(unique_vals, 2))
这里,my_values
是元组的列表,其值为:
[(1, 2), (1, 3), (1, 4), (1, 5),
(2, 3), (2, 4), (2, 5),
(3, 4), (3, 5),
(4, 5)]
说明:
用于计算边界值:
# 1st list
>>> a[0]
[1, 1, 2, 2, 3, 3, 3]
# Last list
>>> a[-1]
[1, 1, 2, 2, 5, 5, 5]
# all the 0th elements of sub-lists excluding 1st and last list
>>> [sub_list[0] for sub_list in a[1:-1]]
[1]
# all the last elements of sub-lists excluding 1st and last list
>>> [sub_list[-1] for sub_list in a[1:-1]]
[4]
添加上述所有列表,将给出边界元素。以下是一些部分硬编码的易于理解的方法
- 编辑:由于预处理,版本更快
- 编辑2:最后一次加速(预处理中的对称性降低)
- 编辑3:正常;在预处理中又增加了一个对称性缩减步骤
方法
- 通过浏览获取块视图
- 对邻域逻辑预处理一次:
- 创建所有索引的列表,以便在给定窗口中查找对(已连接)
- 使用了一些对称约化
- 迭代所有块;抓取配对
- 如果某个对称约束为真,则添加
代码
用于表示为图像的图像
hmm。。。在你的情况下,touch
(正式)意味着什么?我的错误;'“触摸”表示它位于该元素每个外观周围的3x3正方形内。这些(1,4)
和(3,5)
看起来不正确,或者它们(至少在非包裹场景中)看起来不正确?
import numpy as np
from skimage.util.shape import view_as_blocks, view_as_windows
img = np.array([[1,1,2,2,3,3,3],
[1,1,1,1,2,4,4],
[1,1,2,2,5,5,5]])
#img = np.random.random_integers(1, 10, size=(256,256))
WINDOW_SIZE = 3
img_windowed = view_as_windows(img, window_shape=(WINDOW_SIZE,WINDOW_SIZE)) # overlapping
# Preprocessing: generate valid index_pairs
index_pairs = []
for x in range(WINDOW_SIZE):
for y in range(WINDOW_SIZE):
if y>=x: # remove symmetries
if x>0:
index_pairs.append(((x,y), (x-1,y)))
if x<2:
index_pairs.append(((x,y), (x+1,y)))
if y>0:
index_pairs.append(((x,y), (x,y-1)))
if y<2:
index_pairs.append(((x,y), (x,y+1)))
if x>0 and y>0:
index_pairs.append(((x,y), (x-1,y-1)))
if x<2 and y<2:
index_pairs.append(((x,y), (x+1,y+1)))
if x>0 and y<2:
index_pairs.append(((x,y), (x-1,y+1)))
if x<2 and y>0:
index_pairs.append(((x,y), (x+1,y-1)))
index_pairs = list(filter(lambda x: x[0] < x[1], index_pairs)) # remove symmetries
pairs = []
def reason_pair(a,b): # remove symmetries
if a<b:
pairs.append((a,b))
elif a>b:
pairs.append((b,a))
for a in range(img_windowed.shape[0]):
for b in range(img_windowed.shape[1]):
block = img_windowed[a,b]
for i in index_pairs:
reason_pair(block[i[0]], block[i[1]])
print(set(pairs))
set([(1, 2), (1, 3), (4, 5), (1, 5), (2, 3), (2, 5), (3, 4), (2, 4)])