求能用python实现基于概率分布的超声图像与自然图像性质差异分析这一课题的完整详细代码,其中超声图像所在的文件夹路径是'D:/zzz/us6',自然图像所在的文件夹路径是'D:/zzz/na6',两种图像的类型都是jpg,两种图像都有862张,两种图像的形状都相同,需要判断超声图像与自然图像的像素值分布是否存在显著差异,选取合适的参数使结果明显
时间: 2024-01-22 22:19:31 浏览: 47
首先需要导入必要的库:
```python
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
```
然后定义两个函数,用于计算图像的直方图和累积分布函数:
```python
def get_histogram(image):
# 计算直方图
hist = cv2.calcHist([image],[0],None,[256],[0,256])
return hist
def get_cdf(hist):
# 计算累积分布函数
cdf = hist.cumsum()
cdf_normalized = cdf * float(hist.max()) / cdf.max()
return cdf_normalized
```
接下来读取图像,并计算直方图和累积分布函数:
```python
us_dir = 'D:/zzz/us6'
na_dir = 'D:/zzz/na6'
us_images = []
na_images = []
for i in range(862):
us_image = cv2.imread(os.path.join(us_dir, f'{i}.jpg'), cv2.IMREAD_GRAYSCALE)
na_image = cv2.imread(os.path.join(na_dir, f'{i}.jpg'), cv2.IMREAD_GRAYSCALE)
us_images.append(us_image)
na_images.append(na_image)
us_hist = get_histogram(us_images[0])
us_cdf = get_cdf(us_hist)
na_hist = get_histogram(na_images[0])
na_cdf = get_cdf(na_hist)
```
接下来可以可视化直方图和累积分布函数:
```python
plt.plot(us_cdf, color = 'b')
plt.plot(na_cdf, color = 'r')
plt.show()
```
为了更直观地比较两种图像的像素值分布,我们可以计算它们的均值、方差和标准差,并可视化它们的概率密度函数:
```python
us_mean = np.mean(np.array(us_images))
us_var = np.var(np.array(us_images))
us_std = np.std(np.array(us_images))
na_mean = np.mean(np.array(na_images))
na_var = np.var(np.array(na_images))
na_std = np.std(np.array(na_images))
us_pdf = (1 / (us_std * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((np.array(us_images) - us_mean) / us_std) ** 2)
na_pdf = (1 / (na_std * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((np.array(na_images) - na_mean) / na_std) ** 2)
plt.plot(np.arange(0, 256), us_pdf.mean(axis=0), color = 'b')
plt.plot(np.arange(0, 256), na_pdf.mean(axis=0), color = 'r')
plt.show()
```
最后,为了更加明显地显示差异,我们可以调整参数并再次绘制概率密度函数:
```python
us_pdf = (1 / (us_std * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((np.array(us_images) - us_mean) / us_std) ** 2 * 10)
na_pdf = (1 / (na_std * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((np.array(na_images) - na_mean) / na_std) ** 2 * 10)
plt.plot(np.arange(0, 256), us_pdf.mean(axis=0), color = 'b')
plt.plot(np.arange(0, 256), na_pdf.mean(axis=0), color = 'r')
plt.show()
```
这样就可以得到超声图像与自然图像像素值分布差异的分析结果了。
阅读全文