kmeans+分类

#-*- encoding:utf-8 -*-
__date__ = '17/04/21'
'''
CV_INTER_NN - 最近邻插值,  
CV_INTER_LINEAR - 双线性插值 (缺省使用)  
CV_INTER_AREA - 使用象素关系重采样。当图像缩小时候,该方法可以避免波纹出现。当图像放大时,类似于 CV_INTER_NN 方法..  
CV_INTER_CUBIC - 立方插值
'''
 
import os, codecs
from cv2 import cv2
import numpy as np
from sklearn.cluster import KMeans

def get_file_name(path):
    classes=os.listdir(path)
    category=[classes[0],classes[18]]   #数据集中的0和18两类
    path_filenames = []
    filename_list = []
    for file in category:
        pathh=os.path.join(path, file)
        pics=os.listdir(pathh)
        for pic in pics:
            if not pic.startswith('.'):
                path_filenames.append(os.path.join(pathh, pic))
                filename_list.append(pic)

    return path_filenames
def knn_detect(file_list, cluster_nums, randomState = None):
    features = []
    files = file_list
    sift=cv2.xfeatures2d.SIFT_create()
    for file in files:
        print(file)
        img = cv2.imread(file)
        img = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)
		
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        print(gray.dtype)
        _, des = sift.detectAndCompute(gray, None)
		
        if des is None:
            file_list.remove(file)
            continue
 
        reshape_feature = des.reshape(-1, 1)
        features.append(reshape_feature[0].tolist())
 
    input_x = np.array(features)
 
    kmeans = KMeans(n_clusters = cluster_nums, random_state = randomState).fit(input_x)
	
    return kmeans.labels_, kmeans.cluster_centers_
 
def res_fit(filenames, labels):
	
	files = [file.split('/')[-1] for file in filenames]
 
	return dict(zip(files, labels))
 
def save(path, filename, data):
	file = os.path.join(path, filename)
	with codecs.open(file, 'w', encoding = 'utf-8') as fw:
		for f, l in data.items():
			fw.write("{}\t{}\n".format(f, l))
 
def main():
	path_filenames = get_file_name("/home/xiaozhen/UCMerced_LandUse/Images/")
   #下载的数据集的路径(需要改)
	labels, cluster_centers = knn_detect(path_filenames, 2)
 
	res_dict = res_fit(path_filenames, labels)
	save('./', 'knn_res.txt', res_dict)
 
if __name__ == "__main__":
	main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值