一段对图片按照rgb颜色聚类的python代码

来源:互联网 发布:python图片文字识别 编辑:程序博客网 时间:2024/06/15 09:21
一段对图片按照rgb颜色聚类的代码,运行命令为:python get_color_feature.py --image=./diffculty/342940_1_1.png结果为显示3张图,分别是原图、剪切缩放后的图、取出聚类出的第二大类的mask本代码时为了验证利用rgb(或者其他颜色空间聚类的效果),感兴趣的朋友可以试试# import the necessary packagesfrom skimage.exposure import rescale_intensityfrom skimage.segmentation import slicfrom skimage.util import img_as_floatfrom skimage import ioimport numpy as npimport argparseimport cv2import scipyimport scipy.cluster.hierarchy as schimport argparse# 参数操作,ap = argparse.ArgumentParser()ap.add_argument("-i","--image",required=True,help="path to input image")args = vars(ap.parse_args())# 读入图片oimage = cv2.imread(args["image"])# 将图片缩放至[150,200],降低聚类的复杂度,提高运行速度orig = cv2.resize(oimage,(150,200),interpolation=cv2.INTER_CUBIC)# 初始化显示模块vis = np.zeros(orig.shape[:2],dtype="float")# 定义图片剪切范围的起点x=0y=0# 剪切图片points = np.array(orig[x:,y:,:])points.shape=((orig.shape[0]-x)*(orig.shape[1]-y),3)print points.shape# 级联聚类disMat =sch.distance.pdist(points,'euclidean')Z = sch.linkage(disMat,method='average')cluster = sch.fcluster(Z,t=1,criterion='inconsistent')# 输出每个元素的类别号print "original cluster by hierarchy clustering:\n:",clusterprint cluster.shape# 找出含有元素数目最多的类别cluster_tmp=clusterprint "max value: ",np.max(cluster)count = np.bincount(cluster)#index = np.argmax(count)count[np.argmax(count)]=-1#count[np.argmax(count)]=-1 # 此每多运行n次,就是取含元素数目第n+1多的类别print "max count value: ",np.argmax(count)cluster_tmp.shape=([orig.shape[0]-x,orig.shape[1]-y])# 将相应类别的点映射到vis矩阵中vis[cluster_tmp == np.argmax(count)] = 1vis.shape=[orig.shape[0]-x,orig.shape[1]-y]# 为了方便opencv显示,我们需要将vis数值归一化到0-255的整形vis = rescale_intensity(vis, out_range=(0,255)).astype("uint8")# 图片显示cv2.imshow("Input",oimage) # 显示原图orig_cut = pointsorig_cut.shape=(orig.shape[0]-x,orig.shape[1]-y,3)# 显示剪切图cv2.imshow("cut",cv2.resize(orig_cut,(oimage.shape[1],oimage.shape[0]),interpolation=cv2.INTER_CUBIC))cv2.imshow("vis",cv2.resize(vis,(oimage.shape[1],oimage.shape[0]),interpolation=cv2.INTER_CUBIC))cv2.waitKey(0)

原创粉丝点击