如何创建uint16高斯噪声图像?

2024-04-26 03:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个定义了均值和标准差的高斯噪声的uint16图像。你知道吗

我已经尝试使用numpy的random.normal来实现这个,但是它返回一个float64数组:

mu = 10
sigma = 100
shape = (1024,1024)
gauss_img = np.random.normal(mu, sigma, shape)

print(gauss_img.dtype)

>>> dtype('float64')

有没有办法将gauss_img转换成uint16数组,同时保留原始的平均值和标准差?或者有没有另一种方法可以完全创建uint16噪声图像?你知道吗

编辑:正如评论中提到的,np.random.normal将不可避免地对给定sd>;平均值的负值进行采样,这对于转换为uint16是个问题。你知道吗

所以我想我需要一个不同的方法来直接创建一个无符号的高斯图像。你知道吗


Tags: 图像imgnprandom数组噪声sigmanormal
3条回答

如果有一系列uint16数字要从中采样,那么应该检查this post。你知道吗

这样就可以使用scipy.stats.truncnorm生成无符号整数的高斯分布。你知道吗

有了这个平均值和sigma,你一定会得到一些负值。所以我猜你可以选择,在采样之后,找到最负的值,然后把它的绝对值加到所有的样本中。之后,按照注释中的建议转换为uint。当然,你这样做是不公平的。你知道吗

所以我觉得这和你要找的很接近。你知道吗

导入库并伪造一些扭曲的数据。这里,由于输入的来源未知,所以我使用np.expm1(np.random.normal())创建了倾斜数据。您也可以使用skewnorm().rvs(),但这是一种欺骗,因为这也是您用来描述它的库。你知道吗

我将原始样本展平以使绘制直方图更容易。你知道吗

import numpy as np
from scipy.stats import skewnorm

# generate dummy raw starting data
# smaller shape just for simplicity
shape = (100, 100)
raw_skewed = np.maximum(0.0, np.expm1(np.random.normal(2, 0.75, shape))).astype('uint16')

# flatten to look at histograms and compare distributions
raw_skewed = raw_skewed.reshape((-1))

现在找到描述倾斜数据的参数,并使用这些参数创建一个新的分布来采样,希望它能很好地匹配原始数据。你知道吗

我想这两行代码就是你想要的。

# find params
a, loc, scale = skewnorm.fit(raw_skewed)

# mimick orig distribution with skewnorm
new_samples = skewnorm(a, loc, scale).rvs(10000).astype('uint16')

现在绘制每一个的分布以进行比较。你知道吗

plt.hist(raw_skewed, bins=np.linspace(0, 60, 30), hatch='\\', label='raw skewed')
plt.hist(new_samples, bins=np.linspace(0, 60, 30), alpha=0.65, color='green', label='mimic skewed dist')
plt.legend()

enter image description here

直方图非常接近。如果这看起来足够好,请将新数据重塑为所需的形状。你知道吗

# final result
new_samples.reshape(shape)

现在。。。这是我认为可能不够的地方。看一看每个人的热图。原始分布有一个较长的尾部(更多的离群值没有被skewnorm()描述)。你知道吗

这将绘制出每种类型的热图。你知道吗

# plot heatmaps of each
fig = plt.figure(2, figsize=(18,9))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)

im1 = ax1.imshow(raw_skewed.reshape(shape), vmin=0, vmax=120)
ax1.set_title("raw data - mean: {:3.2f}, std dev: {:3.2f}".format(np.mean(raw_skewed), np.std(raw_skewed)), fontsize=20)

im2 = ax2.imshow(new_samples.reshape(shape), vmin=0, vmax=120)
ax2.set_title("mimicked data - mean: {:3.2f}, std dev: {:3.2f}".format(np.mean(new_samples), np.std(new_samples)), fontsize=20)

plt.tight_layout()

# add colorbar
fig.subplots_adjust(right=0.85)
cbar_ax = fig.add_axes([0.88, 0.1, 0.08, 0.8])  # [left, bottom, width, height]
fig.colorbar(im1, cax=cbar_ax)

看着它。。。您可以看到偶尔出现的黄色斑点,表示原始分布中的值非常高,无法进入输出。这也显示在输入数据的更高的标准偏差中(参见每个热图中的标题,但同样,如对原始问题的评论中。。。均值和标准差并不是真正的分布特征,因为它们不是正态分布。。。但它们是相对比较的)。你知道吗

但是。。。这就是我为入门而创建的非常具体的倾斜示例的问题。希望这里有足够的资源来处理和调整,直到它满足您的需求和特定的数据集。祝你好运!你知道吗

enter image description here

相关问题 更多 >

    热门问题