标签:des style blog http color 使用
这是一个按照图片颜色深浅的聚类算法
1 function [ result ] = my_kcluster_random( imgAddress ) 2 %UNTITLED Summary of this function goes here 3 % Detailed explanation goes here 4 img_original = imread(imgAddress); %读入图像 5 img_gray = rgb2gray(img_original); 6 [m, n] = size(img_gray); 7 temp = zeros(m*n,1); 8 temp_one = zeros(m*n,1); 9 temp_two = zeros(m*n,1); 10 % 将图像进行RGB——3通道分解 11 R = reshape(img_original(:, :, 1), m*n, 1); % 将RGB分量各转为kmeans使用的数据格式n行,一样一样本 12 G = reshape(img_original(:, :, 2), m*n, 1); 13 B = reshape(img_original(:, :, 3), m*n, 1); 14 dR = double(R); 15 dG = double(G); 16 dB = double(B); 17 x1 = 1; 18 temp(x1) = 1; 19 temp_one(1) = x1; 20 mn = m * n; 21 max = 0.0; 22 i = 1; 23 for k = 1 : mn %选取第二个类的初始点 24 dist = sqrt((dR(x1)-dR(k))^2 + (dG(x1)-dG(k))^2 + (dB(x1)-dB(k))^2); 25 if(dist > max) 26 max = dist; 27 i = k; 28 end 29 end 30 x2 = i; 31 temp(x2) = 2; 32 temp_two(1) = x2; 33 one = 1; 34 two = 1; 35 dist_cluster_one = 65535; 36 dist_cluster_two = 65535; 37 for k = 1 : mn %聚类 38 if(temp(k) == 0 && x1 > 0 && x2 > 0) 39 dist_cluster_one = sqrt((dR(x1)-dR(k))^2 + (dG(x1)-dG(k))^2 + (dB(x1)-dB(k))^2); 40 dist_cluster_two = sqrt((dR(x2)-dR(k))^2 + (dG(x2)-dG(k))^2 + (dB(x2)-dB(k))^2); 41 end 42 if(dist_cluster_one < dist_cluster_two) 43 temp(k) = 1; 44 one = one + 1; 45 temp_one(one) = k; 46 else 47 temp(k) = 2; 48 two = two + 1; 49 temp_two(two) = k; 50 end 51 x1 = rand(1,1) * one; 52 x1 = int8(x1) + 1; 53 x1 = temp_one(x1); 54 x2 = rand(1,1) * two; 55 x2 = int8(x2) + 1; 56 x2 = temp_two(x2); 57 end 58 for k = 1 : mn %将其中一类用红色点显示 59 if(temp(k) == 1) 60 R(k) = 0; 61 G(k) = 0; 62 B(k) = 0; 63 end 64 end 65 66 for k = 1 : mn %将其中一类用红色点显示 67 if(temp(k) == 2) 68 R(k) = 255; 69 G(k) = 255; 70 B(k) = 255; 71 end 72 end 73 74 dat = [R, G, B]; 75 result = reshape(dat,m,n,3); 76 77 end
对文件夹中的图片处理
1 function [ output_args ] = ccluster_compare( ) 2 %UNTITLED5 Summary of this function goes here 3 % Detailed explanation goes here 4 pictures1 = dir(‘C:\Users\george\Desktop\obj1\*.png‘); 5 pictures2 = dir(‘C:\Users\george\Desktop\obj2\*.png‘); 6 [rp cp] = size(pictures1); 7 for i = 1:rp 8 img = strcat(‘C:\Users\george\Desktop\obj1\‘,pictures1(i).name); 9 result = my_cluster(img); 10 img = strcat(‘C:\Users\george\Desktop\obj1\1obj\‘,pictures1(i).name); 11 saveas(result,img); 12 img = strcat(‘C:\Users\george\Desktop\obj2\‘,pictures2(i).name); 13 result = my_cluster(img); 14 img = strcat(‘C:\Users\george\Desktop\obj2\2obj\‘,pictures1(i).name); 15 saveas(result,img); 16 end 17 end
标签:des style blog http color 使用
原文地址:http://www.cnblogs.com/george-cw/p/3833678.html