KMeans与标签数据聚类

如何解决KMeans与标签数据聚类

我有一个形状为(587,987,3)的RGB图像。 #height,width,num_channels

我还具有7个类别中每个类别的标签数据(像素位置)。

我想应用KMeans聚类算法将给定图像分为7类。 在应用KMeans聚类时,我想利用标签数据,即像素位置。

如何利用标签数据?

到目前为止,我尝试过的方法如下。

img = np.random.randint(low=1,high=99,size=(587,987,3)) 

im = img.reshape(img.shape[0]*img.shape[1],img.shape[2])
im = StandardScaler().fit_transform(im)

clusters = KMeans(n_clusters=7,n_init= 100,max_iter=100,n_jobs=-1).fit(im)
kmeans_labels = clusters.labels_.reshape(img.shape[0],img.shape[1])

plt.imshow(kmeans_labels)
plt.show()
   

我正在寻找向其余片段(超像素)传播一些注释

解决方法

正如问题注释中所阐明的那样,您可以使用半监督分类器[1]将聚类视为超像素,并将标签从几个样本传播到剩余数据。

创建图像以运行示例:

import numpy as np
from skimage.data import binary_blobs
import cv2 
from pyift.shortestpath import seed_competition
from scipy import sparse,spatial
import matplotlib.pyplot as plt 

# creating noisy image
size = 256 
image = np.empty((size,size,3)) 
image[:,:,0] = binary_blobs(size,seed=0)
image[:,1] = binary_blobs(size,2] = binary_blobs(size,seed=1)
image += np.random.randn(*image.shape) / 10
image -= image.min()
image /= image.max()

plt.axis(False)
plt.imshow(image)
plt.show()

noisy image

计算超像素:

def grid_seeds(image,rows = 15,cols = 15):
    seeds = np.zeros(image.shape[:2],dtype=np.int)
    v_step,h_step = image.shape[0] // rows,image.shape[1] // cols
    count = 1
    for i in range(rows):
        y = v_step // 2 + i * v_step
        for j in range(cols):
            x = h_step // 2 + j * h_step
            seeds[y,x] = count
            count += 1
    return seeds
                                                                                                 
seeds = grid_seeds(image)
_,_,superpixels = seed_competition(seeds,image=image)
superpixels -= 1  # shifting labels to zero

contours,_ = cv2.findContours(superpixels,cv2.RETR_FLOODFILL,cv2.CHAIN_APPROX_SIMPLE)
im_w_contours = image.copy()
cv2.drawContours(im_w_contours,contours,-1,(255,0))

plt.axis(False)
plt.imshow(im_w_contours)
plt.show()

superpixels

从4个任意节点传播标签,每个节点一个(颜色)一个,并用期望的颜色为结果标签着色。

def create_graph(image,labels):
    n_nodes = labels.max() + 1
    h,w,d = image.shape
    avg = np.zeros((n_nodes,d))
    for i in range(h):
        for j in range(w):
            avg[labels[i,j]] += image[i,j]
    avg[:] /= np.bincount(labels.flat)[:,np.newaxis]  # ignore label 0
    graph = spatial.distance_matrix(avg,avg)
    return sparse.csr_matrix(graph)

graph = create_graph(image,superpixels)

graph_seeds = np.zeros(graph.shape[0],dtype=np.int)
graph_seeds[1] = 1   # blue training sample
graph_seeds[3] = 2   # yellow training sample
graph_seeds[13] = 3  # white training sample
graph_seeds[14] = 4  # black training sample

label_colors = {1: (0,255),2: (255,255,0),3: (255,4: (0,0)}

_,labels = seed_competition(graph_seeds,graph=graph)

result = np.empty_like(image)
for i,lb in enumerate(labels):
    result[superpixels == i] = label_colors[lb]

plt.axis(False)
plt.imshow(result)
plt.show()

result

在此示例中,我将每个超像素的平均颜色之间的差异用作其弧线权重。但是,在实际问题中,将需要一些更精细的特征向量。

此外,标记的数据是图像超像素的子集,但这不是绝对必要的,您可以在对图形进行建模时添加任何人工节点,尤其是作为种子节点。

这种方法常用于遥感中,本文可能与之相关[2]。

[1] Amorim,W. P.,Falcão,A. X.,Papa,J. P.和Carvalho,M. H.(2016)。通过最佳连接性改善半监督学习。模式识别,60,72-85。

[2] Vargas,John E.等人。 “基于超像素的超高分辨率图像的交互式分类。” 2014年第27届SIBGRAPI图形,图案和图像会议。 IEEE,2014年。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-