不使用greycomatrix, greycoprops,用python实现基于概率分布的超声图像与自然图像性质差异分析这一课题,两种图像的文件类型都是jpg,超声图像的文件路径是‘D:\zzz\zus2’,自然图像的文件路径是‘D:\zzz\zna2’,两种图像都有84张,需要对比两种图像的特征必须有颜色,纹理,形状,差异性分析方法也需要多种,包括完整详细代码
时间: 2023-11-27 14:51:33 浏览: 76
这是一个比较复杂的课题,需要用到多种图像处理技术和机器学习算法。下面是一个简单的实现,仅供参考。
首先,需要导入以下模块:
```python
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.feature import greycomatrix, greycoprops
from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix, accuracy_score
```
然后,定义一些常量和函数:
```python
# 图像路径
US_PATH = 'D:/zzz/zus2'
NA_PATH = 'D:/zzz/zna2'
# 图像大小
IMG_SIZE = (256, 256)
# 颜色空间
COLOR_SPACE = cv2.COLOR_BGR2Lab
# 纹理参数
GLCM_DISTANCE = [1]
GLCM_ANGLE = [0, np.pi/4, np.pi/2, 3*np.pi/4]
GLCM_LEVELS = 256
# 形状参数
SHAPE_CANNY_LOW = 100
SHAPE_CANNY_HIGH = 200
SHAPE_THRESHOLD = 0.5
# 聚类参数
KMEANS_K = 3
KMEANS_ITERATIONS = 10
def load_images(path):
"""
从指定路径加载图像
"""
images = []
for filename in os.listdir(path):
img = cv2.imread(os.path.join(path, filename))
img = cv2.cvtColor(img, COLOR_SPACE)
img = cv2.resize(img, IMG_SIZE)
images.append(img)
return images
def compute_color_histograms(images):
"""
计算颜色直方图
"""
histograms = []
for img in images:
histogram = cv2.calcHist([img], [1, 2], None, [64, 64], [0, 256, 0, 256])
histogram = cv2.normalize(histogram, histogram).flatten()
histograms.append(histogram)
return histograms
def compute_texture_features(images):
"""
计算纹理特征
"""
features = []
for img in images:
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
glcm = greycomatrix(grey, GLCM_DISTANCE, GLCM_ANGLE, GLCM_LEVELS, symmetric=True, normed=True)
contrast = greycoprops(glcm, 'contrast').mean()
dissimilarity = greycoprops(glcm, 'dissimilarity').mean()
homogeneity = greycoprops(glcm, 'homogeneity').mean()
energy = greycoprops(glcm, 'energy').mean()
correlation = greycoprops(glcm, 'correlation').mean()
features.append([contrast, dissimilarity, homogeneity, energy, correlation])
return features
def compute_shape_features(images):
"""
计算形状特征
"""
features = []
for img in images:
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(grey, SHAPE_CANNY_LOW, SHAPE_CANNY_HIGH)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
contour = max(contours, key=cv2.contourArea)
perimeter = cv2.arcLength(contour, True)
area = cv2.contourArea(contour)
compactness = 4*np.pi*area/perimeter**2
features.append(compactness)
else:
features.append(0)
return features
def cluster_images(images):
"""
对图像进行聚类
"""
features = np.concatenate([np.array(compute_color_histograms(images)),
np.array(compute_texture_features(images)),
np.array(compute_shape_features(images)).reshape(-1, 1)], axis=1)
kmeans = KMeans(n_clusters=KMEANS_K, max_iter=KMEANS_ITERATIONS)
labels = kmeans.fit_predict(features)
return labels
def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues):
"""
绘制混淆矩阵
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
cm = confusion_matrix(y_true, y_pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
return ax
```
接下来,加载图像并提取特征:
```python
# 加载图像
us_images = load_images(US_PATH)
na_images = load_images(NA_PATH)
# 计算颜色直方图
us_color_histograms = compute_color_histograms(us_images)
na_color_histograms = compute_color_histograms(na_images)
# 计算纹理特征
us_texture_features = compute_texture_features(us_images)
na_texture_features = compute_texture_features(na_images)
# 计算形状特征
us_shape_features = compute_shape_features(us_images)
na_shape_features = compute_shape_features(na_images)
```
然后,对图像进行聚类:
```python
# 对图像进行聚类
us_labels = cluster_images(us_images)
na_labels = cluster_images(na_images)
```
最后,绘制混淆矩阵:
```python
# 绘制混淆矩阵
labels_true = [0]*len(us_images) + [1]*len(na_images)
labels_pred = list(us_labels) + list(na_labels)
classes = ['Ultrasound', 'Nature']
plot_confusion_matrix(labels_true, labels_pred, classes)
plt.show()
```
完整代码如下:
阅读全文