专栏名称: 小白学视觉
本公众号主要介绍机器视觉基础知识和新闻,以及在学习机器视觉时遇到的各种纠结和坑的心路历程。
目录
相关文章推荐
Excel之家ExcelHome  ·  WPS表格中的几个常用函数公式 ·  昨天  
Excel之家ExcelHome  ·  接入DeepSeek以后,我的Excel真的 ... ·  2 天前  
Excel之家ExcelHome  ·  告别DeepSeek ... ·  4 天前  
Excel之家ExcelHome  ·  70岁老妈用DeepSeek变身‘AI达人’ ... ·  5 天前  
Excel之家ExcelHome  ·  教你3分钟将DeepSeek接入到Word, ... ·  4 天前  
51好读  ›  专栏  ›  小白学视觉

使用 Python 和 OpenCV 进行图像聚类

小白学视觉  · 公众号  ·  · 2025-01-07 10:28

正文

点击上方小白学视觉”,选择加"星标"或“置顶

重磅干货,第一时间送达

import numpy as np
import cv2
import matplotlib.pyplot as plt
image=cv2.imread('../input/hillstation/hillstation.jpg')
plt.imshow(image)  #original image
0x7f8efaabf890>

i=image.sum(axis=2#convert the shape of image in 2 dimensions
i.shape
(183275)
img=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
plt.imshow(img) #convert the image into RGB
0x7f8efa9e9550>

vector=img.reshape((-1,3)) #convert the mXNX3 image into kX3 matrix where k=mXn and each row will be a vector in 3 dimensions space
vector
array([[ 55,  61111],
       [ 55,  61111],
       [ 55,  61113],
       ...,
       [ 42,  40,  25],
       [ 35,  33,  18],
       [ 28,  26,  13]], dtype=uint8)
vector=np.float32(vector) #convert the uint8 values to float values. k-means method to opencv
vector
array([[ 55.,  61.111.],
       [ 55.,  61.111.],
       [ 55.,  61.113.],
       ...,
       [ 42.,  40.,  25.],
       [ 35.,  33.,  18.],
       [ 28.,  26.,  13.]], dtype=float32)

#clustering into multiple labels as the picture has multiple colours.
c=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10,1.0)

# first parameter is used for stop the criteria if the accuracy is achieved
# second parameter is used for stop the algorithm after he specified number of iterations

# 'c' is the iteration termination process. When the iteration is satisfied, the algorithm will stop.
k=5 #number of clusters
attempts=10 #number of times the algorithm is executed using different labelings.
ret,label,center=cv2.kmeans(vector,k,None,c,attempts, cv2.KMEANS_PP_CENTERS)

#cv2.kmeans_pp_centers is used to specify how initial centers are taken
center=np.uint8(center)
res=center[label.flatten()] #access the label to regenerate the image
im=res.reshape(img.shape)

#visualization
x=8
y=6
plt.figure(figsize=(x,y))
plt.subplot(1,2,1)
plt.imshow(img)
plt.title('original image')
plt.axis(False)
plt.subplot(1,2,2)
plt.imshow(im)
plt.title('Clustered image')
plt.axis(False)
(-0.5274.5182.5-0.5)

原始图像与聚类图像

下载1:OpenCV-Contrib扩展模块中文版教程
在「小白学视觉」公众号后台回复:扩展模块中文教程即可下载全网第一份OpenCV扩展模块教程中文版,涵盖扩展模块安装、SFM算法、立体视觉、目标跟踪、生物视觉、超分辨率处理等二十多章内容。

下载2:Python视觉实战项目52讲
小白学视觉公众号后台回复:Python视觉实战项目即可下载包括图像分割、口罩检测、车道线检测、车辆计数、添加眼线、车牌识别、字符识别、情绪检测、文本内容提取、面部识别等31个视觉实战项目,助力快速学校计算机视觉。







请到「今天看啥」查看全文