对图像分析聚类

可以读取多张本地或者云端数据集图片,并进行特征提取分析,图像聚类评估的Python代码。

文件下载地址提供

import os
import urllib.request
import numpy as np
import cv2
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score

# 设置要读取的图片文件夹路径
folder_path = "path/to/image/folder"

# 如果图片文件夹不存在,则抛出异常
if not os.path.exists(folder_path):
    raise ValueError("Folder path does not exist")

# 获取文件夹内所有图片文件的路径
image_files = [os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.endswith(".jpg")]

# 定义一个函数来读取和预处理图片
def preprocess_image(image_path):
    # 从文件路径读取图像
    image = cv2.imread(image_path)
    # 转换为灰度图像
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 将图像大小统一调整为 256x256
    resized_image = cv2.resize(gray_image, (256, 256))
    # 将像素值归一化为 [0, 1] 区间
    normalized_image = resized_image.astype(np.float32) / 255.
    # 将 256x256 的图像拉伸为一个 65536 维的向量
    flattened_image = normalized_image.flatten()
    return flattened_image

# 对每个图像进行预处理,并将结果保存在一个 numpy 数组中
preprocessed_images = np.array([preprocess_image(image_path) for image_path in image_files])

# 使用 PCA 进行降维处理
pca = PCA(n_components=50)
reduced_images = pca.fit_transform(preprocessed_images)

# 使用 KMeans 进行聚类,并计算轮廓系数
kmeans = KMeans(n_clusters=5)
cluster_labels = kmeans.fit_predict(reduced_images)
silhouette_avg = silhouette_score(reduced_images, cluster_labels)

# 输出轮廓系数
print("Silhouette Score:", silhouette_avg)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摆烂.MVP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值