otsu阈值分割算法_基于OTSU分割与K-均值聚类的色彩压缩算法

python实现代码位于文章底部^~^

96b192bc48dc0a6d429c6a83b774b218.png

24ae7d8960f260d95a6ef354b6f072dc.png

8ee27534be6f860d2aa4217b90c3e603.png

0c81b50dcfd1a04be35791211f9acfe0.png

c7eca3654601618aa80379036b40967c.png

9c5c1f131afb4ceae617e9c2d8bfa63e.png

989e29b1cc59acc2a745249b570ff6f3.png

3.2数据处理

由于本文关注点在于提取服装类图片主题的颜色信息,所以需要先使用OTSU阈值分割算法提取出图像的前景(如图2先算出最优阈值),然后将前景像素矩阵转换成像素点的列表,然后对前景图像进行RGB空间转HSV空间,再进行非等间隔量化处理(如图3和4)。

856e010fe7da332108f360484e618976.png
图2 OTSU求最优阈值

e4b5a6760a246f0a858cbf93c65c8f84.png
图3 量化前的颜色直方图

d351ece838434a66bf7ce95f222d58e5.png
图4 量化后的颜色特征直方图

3.3 对比实验

图5-1,图6-1,图7-1,图8-1为对“整张图像”的色彩进行聚类的结果图,图5-2,图6-2,图7-2,图8-2为只对“前景图像”的色彩进行聚类的结果图。

图5-1为对整张图片色彩聚类后并且各个类中的点的像素值被各自聚类中心点的像素值取代后的图像,与原图相比,很明显的看出聚类的效果还是较好的,而图5-2为只对前景衣服主题进行色彩聚类并且各个类中的点的像素值被各自聚类中心点的像素值取代后的图片,由于本算法是将前景中的像素点(坐标及RGB值)抽取出来进行聚类,所以导致图片形状的信息会丢失,所以会出现图5-2所示的图片(看起来已经不是衣服的形状)。

图6-1,图6-2为聚类后,并且各个类中的点的像素值被各自聚类中心点的像素值取代后,将图中各个像素点的立体图可视化,从图中可以看出,同一颜色的点较为明显的聚在一起,而不同颜色的点也较为明显地区分开来。

图7-1,图7-2为图像最终得到的聚类中心点集合,可以看出两者之间的差别还是挺大的。

图8-1,图8-2为主要色占比图,可以看出两者之间的色彩种类及色彩占比均不相同。

04321d970bd49bf9c798e099a02c0592.png
图5-1 聚类后的服装图片

f9547f14cbf2f94d95f8b063f722b05f.png
图5-2聚类后的服装图片

dbf9e0ce31a7ebcb2dac6dd21f97ada7.png
图6-1像素点立体图

7c7dffa6b6e5f5f6b6f99fac5f2aa92c.png
图6-2像素点立体图

83a72ff1a922b59f0d9d78da14c8d952.png
图7-1 聚类中心点

07fa439fe046cb39c71a144584cd4777.png
图7-2 聚类中心点

1fed8e61e20f2731384d7916eff3ca22.png
图8-1 各颜色占比图

3691262cf32cce0c02d0ccbc54b5bfa7.png
图8-2 各颜色占比图

5、结论与展望

本文采用分割算法得出图像的前景,然后采用K-均值聚类算法对前景进行主颜色提取。实验结果似乎还可以,但是该算法中还存在着问题,比如说采用K-均值聚类时,这个K值不太好确定,有些服装图片中色彩很多,这时如果我们设置的K值过小,则会丢失许多颜色信息,而且每张图片的主体色彩有多少完全没有一致性,所以我们不可能去设置一个统一的K值,所以我们的算法需要在,如何根据图片大体颜色确定一个相应适合的K值这个问题上进行改进,或许我们需要借助深度学习来训练一个模型,该模型能够对输入的每张彩色图片给出一个适合的K值,或者采用KNN,但这两种方法都需要大量打过标签的数据集,而目前还没有公开的这种数据集,所以在使用这个算法时,我们暂时还需要人工根据输入的图像定义一个K值。

由于颜色特征最能体现一件服装的本质特征,也是最稳定的视觉特征,与图像的其他特征相比,具有尺寸、方向、视觉依赖性较小的特点,所以,未来在服装行业有关颜色特征的提取的发展肯定会越来越快,越来越好。

python代码:

#otsu.py  运行该代码实现otsu方法获取分离前后景的最佳像素值
#coding:utf-8
import cv2
import numpy as np 
from matplotlib import pyplot as plt 

image=cv2.imread("cloth1.jpg")
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

plt.subplot(131)
plt.imshow(image,"gray")
plt.title("source image")
plt.xticks([])
plt.yticks([])

plt.subplot(132)
plt.hist(image.ravel(),256)
plt.title("Histogram")
plt.xticks([])
plt.yticks([])

ret1,th1=cv2.threshold(gray,0,255,cv2.THRESH_OTSU)
#方法选择为THRESH_OTSU
plt.subplot(133)
plt.imshow(th1,"gray")
plt.title("OTSU,threshold is "+str(ret1))
plt.xticks([])
plt.yticks([])
plt.show()

运行结果截图:

72619e27c1bb3996736bcb82bcffa3a3.png
#dominantColors.py
#一个提取图像主颜色的类,有
# -*- coding: utf-8 -*-


import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

class DominantColors:

    CLUSTERS = None
    IMAGE = None
    FLAT_IMAGE = None
    COLORS = None
    LABELS = None
    
    def __init__(self, image, clusters=3):
        self.CLUSTERS = clusters
        self.IMAGE = image
    
    def dominantColors(self):

        img = self.IMAGE
        gray=cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)  //转灰度图
        L,store=[],[]
        for i in range(gray.shape[0]):
            for j in range(gray.shape[1]): 
                if gray[i][j]<156:  
                    L.append((i,j))
        for i in range(img.shape[0]):
            for j in range(img.shape[1]):
                if (i,j) in L:
                    store.append(img[i][j])   //根据最佳前后景分离值将前景的像素值保存下来
        img=np.array(store)
        #reshaping to a list of pixels
        #img = img.reshape((img.shape[0] * img.shape[1], 3))
        
        #save image after operations
        self.FLAT_IMAGE = img
        
        #using k-means to cluster pixels
        kmeans = KMeans(n_clusters = self.CLUSTERS)
        kmeans.fit(img)
        
        #getting the colors as per dominance order
        self.COLORS = kmeans.cluster_centers_
        
        #save labels
        self.LABELS = kmeans.labels_
        
        return self.COLORS.astype(int)
                
    def plotHistogram(self):
       
        #labels form 0 to no. of clusters
        numLabels = np.arange(0, self.CLUSTERS+1)
       
        #create frequency count tables    
        (hist, _) = np.histogram(self.LABELS, bins = numLabels)
        hist = hist.astype("float")
        hist /= hist.sum()
        
        #appending frequencies to cluster centers
        colors = self.COLORS
        
        #descending order sorting as per frequency count
        colors = colors[(-hist).argsort()]
        hist = hist[(-hist).argsort()] 
        
        #creating empty chart
        chart = np.zeros((50, 500, 3), np.uint8)
        start = 0
        
        #creating color rectangles
        for i in range(self.CLUSTERS):
            end = start + hist[i] * 500
            
            #getting rgb values
            r = colors[i][0]
            g = colors[i][1]
            b = colors[i][2]
            
            #using cv2.rectangle to plot colors
            cv2.rectangle(chart, (int(start), 0), (int(end), 50), (r,g,b), -1)
            start = end	
        
        #display chart
        plt.figure()
        plt.axis("off")
        plt.imshow(chart)
        plt.show()
        
    def rgb_to_hex(self, rgb):
        return '#%02x%02x%02x' % (int(rgb[0]), int(rgb[1]), int(rgb[2]))
    
    def plotClusters(self):
        #plotting 
        fig = plt.figure()
        ax = Axes3D(fig)        
        for label, pix in zip(self.LABELS, self.FLAT_IMAGE):
            ax.scatter(pix[0], pix[1], pix[2], color = self.rgb_to_hex(self.COLORS[label]))
        plt.show()
        
    def colorPixels(self):
        
        shape = self.IMAGE.shape
        
        img = np.zeros((shape[0] * shape[1], 3))
        labels = self.LABELS

        for i,color in enumerate(self.COLORS):
            
            indices = np.where(labels==i)[0]
            
            for index in indices:
                img[index] = color
        
        img = img.reshape((shape[0], shape[1], 3)).astype(int)
        
        #display img
        plt.figure()
        plt.axis("off")
        plt.imshow(img)
        plt.show()
        
#colorPixels.py
# -*- coding: utf-8 -*-

from dominantColors import DominantColors
import cv2

#open image
img = 'cloth1.jpg'
img = cv2.imread(img)

#在OpenCV中,图像是用BGR来存贮的
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

#no. of clusters
clusters = 5

#initialize using constructor
dc = DominantColors(img, clusters)

#print dominant colors
colors = dc.dominantColors()
print(colors)

#display clustered points
dc.colorPixels()
#example.py    
# -*- coding: utf-8 -*-

from dominantColors import DominantColors
import cv2

#open image
img = 'cloth1.jpg'
img = cv2.imread(img)

#convert to RGB from BGR
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

#no. of clusters
clusters = 5

#initialize using constructor
dc = DominantColors(img, clusters)

#print dominant colors
colors = dc.dominantColors()
print(colors)

#display clustered points
dc.plotClusters()

#display dominance order
dc.plotHistogram()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值