对于以矩阵表示的图像,有什么方法可以找到在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)
答案 0 :(得分:1)
您可以使用Optional
来实现此目的。以下是示例代码:
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
是list
的{{1}},其值为:
tuple
<强>解释强>:
用于计算边界值:
[(1, 2), (1, 3), (1, 4), (1, 5),
(2, 3), (2, 4), (2, 5),
(3, 4), (3, 5),
(4, 5)]
添加以上所有列表,将给出边界元素。
答案 1 :(得分:1)
这是一些部分硬编码的易于理解的方法。
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)])