我正在尝试检查矩阵中元素邻域的元素之间的差异是否大于某个容差值,如果是,则在新矩阵中邻域元素的相同索引处给出 1 的值. 不知何故,我总是在新矩阵中得到所有的结果,这是错误的。这是我的代码。另外,我通过将图片转换为矩阵来获得矩阵。
from PIL import Image
import numpy as np
from numpy.lib.stride_tricks import as_strided
imo = Image.open("/home/gauss/Pictures/images.jpg")
matrix_pic = np.array(imo.convert('L')).astype(float)
dim = matrix_pic.shape
# start 1 step out of the outer borders of the matrix
def binary_edges(pic_mat , tolerance):
dim = pic_mat.shape
binary_mat = np.zeros((dim[0],dim[1]))
for i in range(1 , dim[0]-1):
for j in range(1 ,dim[1]-1):
center = pic_mat[i,j]
if (abs(pic_mat[i+1,j] - center ) > tolerance):
binary_mat[i+1,j] = 1
if (abs(pic_mat[i,j+1] - center ) > tolerance):
binary_mat[i,j+1] = 1
if (abs(pic_mat[i+1,j+1] - center ) > tolerance):
binary_mat[i+1,j+1] = 1
if (abs(pic_mat[i-1,j] - center ) > tolerance):
binary_mat[i-1,j] = 1
if (abs(pic_mat[i,j-1] - center ) > tolerance):
binary_mat[i,j-1] = 1
if (abs(pic_mat[i-1,j-1] - center ) > tolerance):
binary_mat[i-1,j-1] = 1
return binary_mat
myarray = binary_edges(matrix_pic, 60)
im = Image.fromarray(myarray)
im.show()