python-前景分割(k_means)

'''
Extract panel :kmeans聚类
'''
import os
import cv2
import numpy as np
import math
def panelAbstract(srcImage):
    #   read pic shape
    print(srcImage.shape)
    imgHeight,imgWidth = srcImage.shape[:2]
    imgHeight = int(imgHeight);imgWidth = int(imgWidth)
    # 均值聚类提取前景:二维转一维
    imgVec = np.float32(srcImage.reshape((-1,3)))
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,10,1.0)
    flags = cv2.KMEANS_RANDOM_CENTERS
    ret,label,clusCenter = cv2.kmeans(imgVec,2,None,criteria,10,flags)
    clusCenter = np.uint8(clusCenter)
    clusResult = clusCenter[label.flatten()]
    imgres = clusResult.reshape((srcImage.shape))
    imgres = cv2.cvtColor(imgres,cv2.COLOR_BGR2GRAY)
    bwThresh = int((np.max(imgres)+np.min(imgres))/2)
    _,thresh = cv2.threshold(imgres,bwThresh,255,cv2.THRESH_BINARY_INV)
    threshRotate = cv2.merge([thresh,thresh,thresh])
    return threshRotate

if __name__=="__main__":
   path='D:/Files/Paper/big_paper/picture/Market-1501-v15.09.15/bounding_box_train/'
   save_path = 'D:/Files/Paper/big_paper/picture/Market-1501-v15.09.15/k_means/mask_train/'

   # path = 'D:/Files/Paper/code/mask/mouse.png'
   for i in os.listdir(path):
       if i.endswith('.jpg'):
           srcImage = cv2.imread(path+i)
           b=panelAbstract(srcImage)
           print(save_path)
           cv2.imwrite(save_path + i, b)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值