对于图像处理工作流程,我需要能够将内核应用于图像以创建新矩阵,如下所示:
对输入的10x10矩阵进行迭代,并在每个位置确定矩阵元素3x3邻域中的范围(最大值与最小值之差),并将此范围存储在新的10x10矩阵中的相应位置。我该怎么办?
如果我有一个4x4矩阵示例:
5 10 9 10
10 9 12 10
4 8 9 10
10 10 8 10
我的函数应该获得该矩阵的3x3子集的范围,以16个元素中的每个元素为中心,并创建一个包含这些范围的新4x4矩阵。以上矩阵的结果应为:
5 7 3 3
6 8 4 3
6 8 4 4
6 6 2 2
我正在尝试在NumPy中实现它,但是如果可以在OpenCV或Skimage中实现,请告诉我。
答案 0 :(得分:1)
在附近的最小值由形态腐蚀给出,而最大值由膨胀引起。这些几乎可以由任何图像处理工具箱(包括OpenCV,SciKit和我自己的PyDIP)来计算。在这里,我将使用SciPy ndimage。膨胀和侵蚀之间的区别就是您所说的“范围”。
from scipy import ndimage
import numpy as np
# a is input array, here 5x5 because it's easy to display to the terminal
a = np.random.randint(30, size=(5,5))
mn = ndimage.grey_erosion(a, size=(3,3))
mx = ndimage.grey_dilation(a, size=(3,3))
b = mx - mn
答案 1 :(得分:0)
import numpy as np
rows = arr.shape[0]
cols = arr.shape[1]
diff = np.zeros(shape=(rows,cols))
for i in range(rows):
for j in range(cols):
if i == 0:
if j== 0:
a = arr[i:i+2, j:j+2]
diff[i][j] = np.amax(a) - np.amin(a)
elif j == cols:
a = arr[i:i+2, j-1:j+1]
diff[i][j] = np.amax(a) - np.amin(a)
else:
a = arr[i:i+2, j-1:j+2]
diff[i][j] = np.amax(a) - np.amin(a)
elif i == rows:
if j== 0:
a = arr[i-1:i+1, j:j+2]
diff[i][j] = np.amax(a) - np.amin(a)
elif j == cols:
a = arr[i-1:i+1, j-1:j+1]
diff[i][j] = np.amax(a) - np.amin(a)
else:
a = arr[i-1:i+1, j-1:j+2]
diff[i][j] = np.amax(a) - np.amin(a)
elif j == 0:
a = arr[i-1:i+2, j:j+2]
diff[i][j] = np.amax(a) - np.amin(a)
elif j == cols:
a = arr[i-1:i+2, j-1:j+1]
diff[i][j] = np.amax(a) - np.amin(a)
else:
a = arr[i-1:i+2, j-1:j+2]
diff[i][j] = np.amax(a) - np.amin(a)
print(diff)