Python;确定并向图像片段添加噪声

Python; Determining and adding noise to image segments

为了掌握编码的技巧,我决定使用 Python/Numpy/SKimage 确定 X 光片特定区域的标准差。首先,我决定使用阈值来获取图像的一部分,这并不难。

然而,此时所有 above/below 阈值都为零,因此包含在我想做的测量中。因此我需要排除数据below/above阈值。

我想它可以创建地图或排除某些值或可能更奇特的解决方案。但是,在这一点上,我认为我可能正朝着错误的方向前进。

我的基础 -

import numpy as np
import matplotlib.pyplot as plt
import imageio

image = imageio.imread('thx.jpg', as_gray=True)
image = image.astype('int32')

test1 = np.array(image, copy=True)
test1[image >= 100] = 0

我正在寻找一种方法来排除数据 above/below 阈值。有人可以向我提供正确方向的小推动吗?

编辑:偶尔在工作中度过轻松的一天真是太好了;我的问题的一个子解决方案是将所有值 greater/smaller 添加到列表中,并从那里确定标准偏差。然而,这给我留下了实施噪声 图像片段的问题。

im_row = image.shape[0]
im_col = image.shape[1]
grthen = []
smlthen = []

for i in range(0,im_col-1):
    for j in range(0,im_row-1):
        if (j > 100):
           grthen.append(j)
        else:
            smlthen.append(j)

print(np.std(smlthen))
print(np.std(grthen))

我认为问题在于您将所有这些像素设置为零,然后尝试从中获取统计信息。相反,意识到 test1[image < 100] 仅指那些低于阈值的像素......所以我认为你可以从中获取统计信息,例如np.std(test1[image < 100])

您可能想看看 scikit-image,其中包含许多用于阈值处理、处理二进制图像、将其用作掩码(这实际上就是您正在做的事情)等的工具。

... determine the standard deviation in a certain area of a x-ray picture using Python/Numpy/SKimage.

让我们先生成一个模拟图像:

In [18]: import numpy as np

In [19]: rows, cols = 4, 4

In [20]: image = np.linspace(0, 1, rows*cols).reshape(rows, cols)

In [21]: np.set_printoptions(precision=2)

In [22]: image
Out[22]: 
array([[0.  , 0.07, 0.13, 0.2 ],
       [0.27, 0.33, 0.4 , 0.47],
       [0.53, 0.6 , 0.67, 0.73],
       [0.8 , 0.87, 0.93, 1.  ]])

让我们通过双阈值定义感兴趣区域:

In [25]: low, high = .3, .6

In [26]: mask = np.logical_and(image > low, image < high)

In [27]: mask
Out[27]: 
array([[False, False, False, False],
       [False,  True,  True,  True],
       [ True, False, False, False],
       [False, False, False, False]])

Boolean indexing 是一种计算感兴趣区域标准偏差的可能方法:

In [29]: image[mask]
Out[29]: array([0.33, 0.4 , 0.47, 0.53])

In [30]: np.std(image[mask])
Out[30]: 0.07453559924999299

将不需要的像素设置为 np.nan 并使用 NumPy 的 nanstd 计算标准差是另一种方法:

In [32]: test1 = np.where(mask, image, np.nan)

In [33]: test1
Out[33]: 
array([[ nan,  nan,  nan,  nan],
       [ nan, 0.33, 0.4 , 0.47],
       [0.53,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan]])

In [34]: np.nanstd(test1)
Out[34]: 0.07453559924999299

... the problem of implementing the noise to the image segments.

您可以使用 scikit-images 的 random_noise to generate a noisy image and then filter out those pixels outside the region of interest through NumPy's where:

In [36]: from skimage.util import random_noise

In [37]: noisy = random_noise(image)

In [38]: noisy
Out[38]: 
array([[0.14, 0.07, 0.17, 0.29],
       [0.34, 0.39, 0.38, 0.53],
       [0.66, 0.73, 0.66, 0.67],
       [0.73, 0.98, 1.  , 0.88]])

In [39]: np.where(mask, noisy, image)
Out[39]: 
array([[0.  , 0.07, 0.13, 0.2 ],
       [0.27, 0.39, 0.38, 0.53],
       [0.66, 0.6 , 0.67, 0.73],
       [0.8 , 0.87, 0.93, 1.  ]])