'''
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)