用python实现基于概率分布的超声图像与自然图像性质差异分析,超声图像的文件路径是D:\zzz\na5,自然图像的文件路径是D:\zzz\us5,两种图像都有778张,请注意每张图像的长和宽不都一样可能需要调整,对比的特征包含纹理和形态,需要可视化使结果尽量明显
时间: 2024-01-24 14:17:08 浏览: 130
基于python实现的使用Keras 库构建用于超声图像神经分割的深度神经网络程序源码.zip
首先,我们需要导入必要的库:numpy、opencv、skimage、matplotlib等。
```python
import numpy as np
import cv2
from skimage import feature, color
import matplotlib.pyplot as plt
```
然后,我们可以编写一个函数来计算每张图像的纹理和形态特征,并将结果可视化。
```python
def analyze_image(img_path):
# 读取图像
img = cv2.imread(img_path)
# 调整图像大小
img = cv2.resize(img, (256, 256))
# 转换为灰度图像
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算纹理特征
glcm = feature.greycomatrix(img_gray, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=256, symmetric=True, normed=True)
contrast = feature.greycoprops(glcm, 'contrast').mean()
correlation = feature.greycoprops(glcm, 'correlation').mean()
energy = feature.greycoprops(glcm, 'energy').mean()
homogeneity = feature.greycoprops(glcm, 'homogeneity').mean()
# 计算形态特征
img_canny = feature.canny(img_gray)
img_hough = cv2.HoughLinesP(img_canny, rho=1, theta=np.pi/180, threshold=50, minLineLength=30, maxLineGap=10)
num_lines = len(img_hough)
line_lengths = np.sqrt(np.sum((img_hough[:,0,:2] - img_hough[:,0,2:]) ** 2, axis=1))
line_angles = np.arctan2(img_hough[:,0,3] - img_hough[:,0,1], img_hough[:,0,2] - img_hough[:,0,0])
line_angles_deg = np.rad2deg(line_angles)
line_angles_deg[line_angles_deg < 0] += 180 # 将角度转换到0-180度范围内
avg_line_length = np.mean(line_lengths)
max_line_length = np.max(line_lengths)
min_line_length = np.min(line_lengths)
avg_line_angle = np.mean(line_angles_deg)
max_line_angle = np.max(line_angles_deg)
min_line_angle = np.min(line_angles_deg)
# 可视化结果
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
ax = axes.ravel()
ax[0].imshow(img)
ax[0].set_title('Original Image')
ax[0].axis('off')
ax[1].imshow(img_canny, cmap=plt.cm.gray)
ax[1].set_title('Canny Edge Detection')
ax[1].axis('off')
plt.show()
print('Contrast: {:.2f}'.format(contrast))
print('Correlation: {:.2f}'.format(correlation))
print('Energy: {:.2f}'.format(energy))
print('Homogeneity: {:.2f}'.format(homogeneity))
print('Number of lines: {}'.format(num_lines))
print('Average line length: {:.2f}'.format(avg_line_length))
print('Max line length: {:.2f}'.format(max_line_length))
print('Min line length: {:.2f}'.format(min_line_length))
print('Average line angle: {:.2f}'.format(avg_line_angle))
print('Max line angle: {:.2f}'.format(max_line_angle))
print('Min line angle: {:.2f}'.format(min_line_angle))
```
接下来,我们可以遍历每张图像,调用上述函数进行特征分析。
```python
# 遍历超声图像并分析特征
for i in range(1, 779):
img_path = 'D:/zzz/na5/{}.jpg'.format(i)
print('Analyzing image {}'.format(img_path))
analyze_image(img_path)
# 遍历自然图像并分析特征
for i in range(1, 779):
img_path = 'D:/zzz/us5/{}.jpg'.format(i)
print('Analyzing image {}'.format(img_path))
analyze_image(img_path)
```
最后,我们可以将结果进行比较,以便更好地了解超声图像和自然图像之间的性质差异。
```python
# 比较结果
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))
ax = axes.ravel()
ax[0].bar(['Contrast', 'Correlation', 'Energy', 'Homogeneity'], [na_contrast.mean(), na_correlation.mean(), na_energy.mean(), na_homogeneity.mean()], width=0.4, color='b')
ax[0].bar(['Contrast', 'Correlation', 'Energy', 'Homogeneity'], [us_contrast.mean(), us_correlation.mean(), us_energy.mean(), us_homogeneity.mean()], width=0.4, color='r')
ax[0].set_title('Texture Features')
ax[0].legend(['Natural Images', 'Ultrasound Images'])
ax[1].bar(['Number of Lines', 'Average Line Length', 'Max Line Length', 'Min Line Length'], [na_num_lines.mean(), na_avg_line_length.mean(), na_max_line_length.mean(), na_min_line_length.mean()], width=0.4, color='b')
ax[1].bar(['Number of Lines', 'Average Line Length', 'Max Line Length', 'Min Line Length'], [us_num_lines.mean(), us_avg_line_length.mean(), us_max_line_length.mean(), us_min_line_length.mean()], width=0.4, color='r')
ax[1].set_title('Shape Features')
ax[1].legend(['Natural Images', 'Ultrasound Images'])
ax[2].imshow(na_texture_diff, cmap=plt.cm.RdYlGn)
ax[2].set_title('Texture Difference')
ax[2].axis('off')
ax[3].imshow(na_shape_diff, cmap=plt.cm.RdYlGn)
ax[3].set_title('Shape Difference')
ax[3].axis('off')
plt.show()
```
完整代码如下:
```python
import numpy as np
import cv2
from skimage import feature, color
import matplotlib.pyplot as plt
def analyze_image(img_path):
# 读取图像
img = cv2.imread(img_path)
# 调整图像大小
img = cv2.resize(img, (256, 256))
# 转换为灰度图像
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算纹理特征
glcm = feature.greycomatrix(img_gray, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=256, symmetric=True, normed=True)
contrast = feature.greycoprops(glcm, 'contrast').mean()
correlation = feature.greycoprops(glcm, 'correlation').mean()
energy = feature.greycoprops(glcm, 'energy').mean()
homogeneity = feature.greycoprops(glcm, 'homogeneity').mean()
# 计算形态特征
img_canny = feature.canny(img_gray)
img_hough = cv2.HoughLinesP(img_canny, rho=1, theta=np.pi/180, threshold=50, minLineLength=30, maxLineGap=10)
num_lines = len(img_hough)
line_lengths = np.sqrt(np.sum((img_hough[:,0,:2] - img_hough[:,0,2:]) ** 2, axis=1))
line_angles = np.arctan2(img_hough[:,0,3] - img_hough[:,0,1], img_hough[:,0,2] - img_hough[:,0,0])
line_angles_deg = np.rad2deg(line_angles)
line_angles_deg[line_angles_deg < 0] += 180 # 将角度转换到0-180度范围内
avg_line_length = np.mean(line_lengths)
max_line_length = np.max(line_lengths)
min_line_length = np.min(line_lengths)
avg_line_angle = np.mean(line_angles_deg)
max_line_angle = np.max(line_angles_deg)
min_line_angle = np.min(line_angles_deg)
# 可视化结果
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
ax = axes.ravel()
ax[0].imshow(img)
ax[0].set_title('Original Image')
ax[0].axis('off')
ax[1].imshow(img_canny, cmap=plt.cm.gray)
ax[1].set_title('Canny Edge Detection')
ax[1].axis('off')
plt.show()
print('Contrast: {:.2f}'.format(contrast))
print('Correlation: {:.2f}'.format(correlation))
print('Energy: {:.2f}'.format(energy))
print('Homogeneity: {:.2f}'.format(homogeneity))
print('Number of lines: {}'.format(num_lines))
print('Average line length: {:.2f}'.format(avg_line_length))
print('Max line length: {:.2f}'.format(max_line_length))
print('Min line length: {:.2f}'.format(min_line_length))
print('Average line angle: {:.2f}'.format(avg_line_angle))
print('Max line angle: {:.2f}'.format(max_line_angle))
print('Min line angle: {:.2f}'.format(min_line_angle))
# 遍历超声图像并分析特征
us_contrast = []
us_correlation = []
us_energy = []
us_homogeneity = []
us_num_lines = []
us_avg_line_length = []
us_max_line_length = []
us_min_line_length = []
for i in range(1, 779):
img_path = 'D:/zzz/na5/{}.jpg'.format(i)
print('Analyzing image {}'.format(img_path))
contrast, correlation, energy, homogeneity, num_lines, avg_line_length, max_line_length, min_line_length = analyze_image(img_path)
us_contrast.append(contrast)
us_correlation.append(correlation)
us_energy.append(energy)
us_homogeneity.append(homogeneity)
us_num_lines.append(num_lines)
us_avg_line_length.append(avg_line_length)
us_max_line_length.append(max_line_length)
us_min_line_length.append(min_line_length)
# 遍历自然图像并分析特征
na_contrast = []
na_correlation = []
na_energy = []
na_homogeneity = []
na_num_lines = []
na_avg_line_length = []
na_max_line_length = []
na_min_line_length = []
for i in range(1, 779):
img_path = 'D:/zzz/us5/{}.jpg'.format(i)
print('Analyzing image {}'.format(img_path))
contrast, correlation, energy, homogeneity, num_lines, avg_line_length, max_line_length, min_line_length = analyze_image(img_path)
na_contrast.append(contrast)
na_correlation.append(correlation)
na_energy.append(energy)
na_homogeneity.append(homogeneity)
na_num_lines.append(num_lines)
na_avg_line_length.append(avg_line_length)
na_max_line_length.append(max_line_length)
na_min_line_length.append(min_line_length)
# 比较结果
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))
ax = axes.ravel()
ax[0].bar(['Contrast', 'Correlation', 'Energy', 'Homogeneity'], [na_contrast.mean(), na_correlation.mean(), na_energy.mean(), na_homogeneity.mean()], width=0.4, color='b')
ax[0].bar(['Contrast', 'Correlation', 'Energy', 'Homogeneity'], [us_contrast.mean(), us_correlation.mean(), us_energy.mean(), us_homogeneity.mean()], width=0.4, color='r')
ax[0].set_title('Texture Features')
ax[0].legend(['Natural Images', 'Ultrasound Images'])
ax[1].bar(['Number of Lines', 'Average Line Length', 'Max Line Length', 'Min Line Length'], [na_num_lines.mean(), na_avg_line_length.mean(), na_max_line_length.mean(), na_min_line_length.mean()], width=0.4, color='b')
ax[1].bar(['Number of Lines', 'Average Line Length', 'Max Line Length', 'Min Line Length'], [us_num_lines.mean(), us_avg_line_length.mean(), us_max_line_length.mean(), us_min_line_length.mean()], width=0.4, color='r')
ax[1].set_title('Shape Features')
ax[1].legend(['Natural Images', 'Ultrasound Images'])
na_texture_diff = np.array([na_contrast, na_correlation, na_energy, na_homogeneity]) - np.array([us_contrast, us_correlation, us_energy, us_homogeneity])
us_texture_diff = np.array([us_contrast, us_correlation, us_energy, us_homogeneity]) - np.array([na_contrast, na_correlation, na_energy, na_homogeneity])
na_shape_diff = np.array([na_num_lines, na_avg_line_length, na_max_line_length, na_min_line_length]) - np.array([us_num_lines, us_avg_line_length, us_max_line_length, us_min_line_length])
us_shape_diff = np.array([us_num_lines, us_avg_line_length, us_max_line_length, us_min_line_length]) - np.array([na_num_lines, na_avg_line_length, na_max_line_length, na_min_line_length])
ax[2].imshow(na_texture_diff, cmap=plt.cm.RdYlGn)
ax[2].set_title('Texture Difference')
ax[2].axis('off')
ax[3].imshow(na_shape_diff, cmap=plt.cm.RdYlGn)
ax[3].set_title('Shape Difference')
ax[3].axis('off')
plt.show()
```
阅读全文