作者:梦蕾AngeL | 来源:互联网 | 2022-12-10 13:03
我们假设我有一个二进制40*40
矩阵.在此矩阵中,值可以是1或0.
我需要解析整个矩阵,对于任何值== 1,应用以下内容:
如果满足以下条件,请保持值= 1,否则将值修改回0:
条件:在N*N
(以当前评估值为中心)的平方中,我可以计算至少M个值== 1.
N和M是可以为算法设置的参数,当然N<20
(在这种情况下)和M<(N*N - 1)
.
显而易见的算法是迭代整个图像,然后每次值== 1.围绕该值执行另一次搜索.它会产生一个O ^ 3复杂的算法.有没有想过提高效率?
编辑:一些代码使这更容易理解.
让我们创建一个随机初始化的40*40矩阵1和0.5%(任意选择)的值为1,95%为0.
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
def display_array(image):
image_display_ready = image * 255
print(image_display_ready)
plt.imshow(image_display_ready, cmap='gray')
plt.show()
image = np.zeros([40,40])
for _ in range(80): # 5% of the pixels are == 1
i, j = np.random.randint(40, size=2)
image[i, j] = 1
# Image displayed on left below before preprocessing
display_array(image)
def cleaning_algorithm_v1(src_image, FAT, LR, FLAG, verbose=False):
"""
FAT = 4 # False Alarm Threshold (number of surrounding 1s pixel values)
LR = 8 # Lookup Range +/- i/j value
FLAG = 2 # 1s pixels kept as 1s after processing are flag with this value.
"""
rslt_img = np.copy(src_image)
for i in range(rslt_img.shape[0]):
for j in range(rslt_img.shape[1]):
if rslt_img[i, j] >= 1:
surrounding_abnormal_pixels = list()
lower_i = max(i - LR, 0)
upper_i = min(i + LR + 1, rslt_img.shape[0])
lower_j = max(j - LR, 0)
upper_j = min(j + LR + 1, rslt_img.shape[1])
abnormal_pixel_count = 0
for i_k in range(lower_i, upper_i):
for j_k in range(lower_j, upper_j):
if i_k == i and j_k == j:
continue
pixel_value = rslt_img[i_k, j_k]
if pixel_value >= 1:
abnormal_pixel_count += 1
if abnormal_pixel_count >= FAT:
rslt_img[i, j] = FLAG
rslt_img[rslt_img != FLAG] = 0
rslt_img[rslt_img == FLAG] = 1
return rslt_img
# Image displayed on right below after preprocessing
display_array(cleaning_algorithm_v1(image, FAT=10, LR=6, FLAG=2))
这给出了以下内容: