聚类图像识别源码(模式识别聚类)
本文目录一览:
- 1、怎么利用模糊C均值聚类实现图像分割啊?具体代码
- 2、用python K值聚类识别图片主要颜色的程序,算法python代码已经有了
- 3、用matlab对简单数字图像进行数字聚类处理代码,最好附上解释说明。谢个大神了。
- 4、有没有可以参考的用MATLAB神经网络实现图像识别的源代码
- 5、matlab图像识别
怎么利用模糊C均值聚类实现图像分割啊?具体代码
%%%%%%%%%%%%%%%模糊聚类%%%%%%%%%%%%%%%%%%%%%%%
clear;
load F:\从0开始\数据\data.txt;
INPUTDATA=data;
%--------原始数据标准化-------%
disp('请选择原始数据标准化方式: ');
disp('1-总和标准化|2-标准差标准化|3-极大值标准化|4-极差标准化');
wayforstand=input('请输入: ');
switch wayforstand
case 1,
DATAFORCLUS=standard_use_sum(INPUTDATA);
case 2,
DATAFORCLUS=standard_use_std(INPUTDATA);
case 3,
DATAFORCLUS=standard_use_max(INPUTDATA);
case 4,
DATAFORCLUS=standard_use_jc(INPUTDATA);
otherwise
error('您的输入不符合要求-执行结束!!!');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%基于模糊等价关系的模糊聚类%%%%%%%%%%%%%%%%%%%%%%
%----------构造相似关系-----------%
numrows=size(DATAFORCLUS,1);
numcols=size(DATAFORCLUS,2);
disp('请选择对象之间相似性统计量的方式: ');
disp('1-相关系数法|2-夹角余弦法|3-指数相似系数法|4-绝对值指数法|5-算术平均最小法|6-最大最小值法|7-绝对值差数法|8-数量积法');
wayforr_ij=input('请输入: ');
switch wayforr_ij
case 1, %-----------------------------------相关系数法
for i=1:numrows,
for j=1:numrows,
meani=mean(DATAFORCLUS(i,:));meanj=mean(DATAFORCLUS(j,:));
simiR(i,j)=sum((DATAFORCLUS(i,:)-meani).*(DATAFORCLUS(j,:)-meanj))/...
(sqrt(sum((DATAFORCLUS(i,:)-meani).^2))*sqrt(sum((DATAFORCLUS(j,:)-meanj).^2)));
end
end
case 2, %-----------------------------------夹角余弦法
for i=1:numrows,
for j=1:numrows,
simiR(i,j)=sum(DATAFORCLUS(i,:).*DATAFORCLUS(j,:))/...
(sqrt(sum(DATAFORCLUS(i,:).*DATAFORCLUS(i,:)))*sqrt(sum(DATAFORCLUS(j,:).*DATAFORCLUS(j,:))));
end
end
case 3, %-----------------------------------指数相似系数法
case 4, %-----------------------------------绝对值指数法
case 5, %-----------------------------------算术平均最小法
case 6, %-----------------------------------最大最小值法
case 7, %-----------------------------------绝对值差数法
case 8, %-----------------------------------数量积法
otherwise
error('您的输入不符合要求-执行结束!!!');
end
%-------改造成等价关系----------%
sign=0;
numselfmul=1;
simiRk=eye(numrows);
equi_tem=simiR;
while sign==0,
for i=1:numrows,
for j=1:numrows,
for c=1:numrows,
rij_temp(c)=min([equi_tem(i,c) equi_tem(c,j)]);
end
simiRk(i,j)=max(rij_temp);
end
end
%--------------%
if sum(sum(simiRk-equi_tem,1))~=0,
numselfmul=numselfmul+1;
equi_tem=simiRk;
else
sign=1;
break
end
%--------------%
end
if sign==1,
disp('从相似矩阵到等价矩阵改造成功!!!');
else
disp('从相似矩阵到等价矩阵改造失败!!!');
end
equiR=simiRk;
numclass=input('请输入聚类数: ');
%---------在不同的截集水平进行聚类--------------%
clasc=0;
comp_vec(1,1:numrows)=0;
index=0;
clasc=0;
tip=0;
alpha=0;
temnumeachclass=0;
while (tip==0),
%alpha=input('请输入进行分类的截集水平λ: ');
%alpha=0.5; %调试
if (alpha0 || alpha1),
error('您输入的截集水平λ不符合分类要求-执行结束!!!');
end
comp_arr=ones(numrows)*alpha;
result_arr=(equiR=comp_arr); %--------------------result_arr判断矩阵
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%捡菜算法
for i=1:numrows,
if sum(comp_vec(1,:)==result_arr(i,:))numrows, %-----------说明没有归类
temnumeachclass=0;
%numeachclass(clasc)=index-temnumeachclass;
temsave=result_arr(i,:);
for j=1:numrows,
if sum(result_arr(j,:)==temsave)==numrows,
index=index+1;
class(index)=j;
result_arr(j,:)=0; %--------------------说明已经被归类
temnumeachclass=temnumeachclass+1;
end
end
clasc=clasc+1;
nec(clasc)=temnumeachclass;
else
continue;
end
end
if clasc=numclass,
tip=1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%当模糊分类的数目小于等于所给出的类数时退出循环体
disp('成功!!!');
else
clear class;
clear numeachclass;
clear nec;
clasc=0;
index=0;
temnumeachclass=0;
alpha=alpha+0.01;
end
end
%----取聚类结果----%
num=0;
n=0;
for i=1:clasc,
for j=1:nec(i),
num=num+1;
n=n+1;
CLUS(n,:)=INPUTDATA(class(num),:);
end
n=n+1;
CLUS(n,:)=inf;
end
%format single(CLUS)
lenexport=size(CLUS,1);
for i=1:lenexport,
RESULT(i,:)=sprintf('%15.2f',CLUS(i,:));
end
RESULT
用python K值聚类识别图片主要颜色的程序,算法python代码已经有了
难得被人求助一次, 这个必须回答一下. 不过你的需求确实没有写得太清楚. 根据k值算法出来的是主要颜色有三个, 所以我把三个颜色都打在记事本里了. 如果和你的需求有误, 请自行解决吧.
另外这里需要用到numpy的库, 希望你装了, 如果没装, 这个直接安装也比较麻烦, 可以看一下portablepython的绿色版。
代码如下:
# -*- coding: utf-8 -*-
import Image
import random
import numpy
class Cluster(object):
def __init__(self):
self.pixels = []
self.centroid = None
def addPoint(self, pixel):
self.pixels.append(pixel)
def setNewCentroid(self):
R = [colour[0] for colour in self.pixels]
G = [colour[1] for colour in self.pixels]
B = [colour[2] for colour in self.pixels]
R = sum(R) / len(R)
G = sum(G) / len(G)
B = sum(B) / len(B)
self.centroid = (R, G, B)
self.pixels = []
return self.centroid
class Kmeans(object):
def __init__(self, k=3, max_iterations=5, min_distance=5.0, size=200):
self.k = k
self.max_iterations = max_iterations
self.min_distance = min_distance
self.size = (size, size)
def run(self, image):
self.image = image
self.image.thumbnail(self.size)
self.pixels = numpy.array(image.getdata(), dtype=numpy.uint8)
self.clusters = [None for i in range(self.k)]
self.oldClusters = None
randomPixels = random.sample(self.pixels, self.k)
for idx in range(self.k):
self.clusters[idx] = Cluster()
self.clusters[idx].centroid = randomPixels[idx]
iterations = 0
while self.shouldExit(iterations) is False:
self.oldClusters = [cluster.centroid for cluster in self.clusters]
print iterations
for pixel in self.pixels:
self.assignClusters(pixel)
for cluster in self.clusters:
cluster.setNewCentroid()
iterations += 1
return [cluster.centroid for cluster in self.clusters]
def assignClusters(self, pixel):
shortest = float('Inf')
for cluster in self.clusters:
distance = self.calcDistance(cluster.centroid, pixel)
if distance shortest:
shortest = distance
nearest = cluster
nearest.addPoint(pixel)
def calcDistance(self, a, b):
result = numpy.sqrt(sum((a - b) ** 2))
return result
def shouldExit(self, iterations):
if self.oldClusters is None:
return False
for idx in range(self.k):
dist = self.calcDistance(
numpy.array(self.clusters[idx].centroid),
numpy.array(self.oldClusters[idx])
)
if dist self.min_distance:
return True
if iterations = self.max_iterations:
return False
return True
# ############################################
# The remaining methods are used for debugging
def showImage(self):
self.image.show()
def showCentroidColours(self):
for cluster in self.clusters:
image = Image.new("RGB", (200, 200), cluster.centroid)
image.show()
def showClustering(self):
localPixels = [None] * len(self.image.getdata())
for idx, pixel in enumerate(self.pixels):
shortest = float('Inf')
for cluster in self.clusters:
distance = self.calcDistance(
cluster.centroid,
pixel
)
if distance shortest:
shortest = distance
nearest = cluster
localPixels[idx] = nearest.centroid
w, h = self.image.size
localPixels = numpy.asarray(localPixels)\
.astype('uint8')\
.reshape((h, w, 3))
colourMap = Image.fromarray(localPixels)
colourMap.show()
if __name__=="__main__":
from PIL import Image
import os
k_image=Kmeans()
path = r'.\\pics\\'
fp = open('file_color.txt','w')
for filename in os.listdir(path):
print path+filename
try:
color = k_image.run(Image.open(path+filename))
fp.write('The color of '+filename+' is '+str(color)+'\n')
except:
print "This file format is not support"
fp.close()
用matlab对简单数字图像进行数字聚类处理代码,最好附上解释说明。谢个大神了。
wave2gray.m
function w = wave2gray(c, s, scale, border)
%WAVE2GRAY Display wavelet decomposition coefficients.
% W = WAVE2GRAY(C, S, SCALE, BORDER) displays and returns a
% wavelet coefficient image.
% EXAMPLES:
% wave2gray(c, s); Display w/defaults.
% foo = wave2gray(c, s); Display and return.
% foo = wave2gray(c, s, 4); Magnify the details.
% foo = wave2gray(c, s, -4); Magnify absolute values.
% foo = wave2gray(c, s, 1, 'append'); Keep border values.
%
% INPUTS/OUTPUTS:
% [C, S] is a wavelet decomposition vector and bookkeeping
% matrix.
%
% SCALE Detail coefficient scaling
%--------------------------------------------------------------------
% 0 or 1 Maximum range (default)
% 2, 3... Magnify default by the scale factor
% -1, -2... Magnify absolute values by abs(scale)
%
% BORDER Border between wavelet decompositions
%--------------------------------------------------------------------
% 'absorb' Border replaces image (default)
% 'append' Border increases width of image
%
% Image W: ------- ------ -------------- -------------------
% | | | |
% | a(n) | h(n) | |
% | | | |
% ------- ------ h(n-1) |
% | | | |
% | v(n) | d(n) | | h(n-2)
% | | | |
% ------- ------ --------------
% | | |
% | v(n-1) | d(n-1) |
% | | |
% -------------- -------------- -------------------
% | |
% | v(n-2) | d(n-2)
% | |
%
% Here, n denotes the decomposition step scale and a, h, v, d are
% approximation, horizontal, vertical, and diagonal detail
% coefficients, respectively.
% Check input arguments for reasonableness.
error(nargchk(2, 4, nargin));
if (ndims(c) ~= 2) | (size(c, 1) ~= 1)
error('C must be a row vector.'); end
if (ndims(s) ~= 2) | ~isreal(s) | ~isnumeric(s) | (size(s, 2) ~= 2)
error('S must be a real, numeric two-column array.'); end
elements = prod(s, 2);
if (length(c) elements(end)) | ...
~(elements(1) + 3 * sum(elements(2:end - 1)) = elements(end))
error(['[C S] must be a standard wavelet ' ...
'decomposition structure.']);
end
if (nargin 2) (~isreal(scale) | ~isnumeric(scale))
error('SCALE must be a real, numeric scalar.');
end
if (nargin 3) (~ischar(border))
error('BORDER must be character string.');
end
if nargin == 2
scale =1; % Default scale.
end
if nargin 4
border = 'absorb'; % Default border.
end
% Scale coefficients and determine pad fill.
absflag = scale 0;
scale = abs(scale);
if scale == 0
scale = 1;
end
[cd, w] = wavecut('a', c, s); w = mat2gray(w);
cdx = max(abs(cd(:))) / scale;
if absflag
cd = mat2gray(abs(cd), [0, cdx]); fill = 0;
else
cd = mat2gray(cd, [-cdx, cdx]); fill = 0.5;
end
% Build gray image one decomposition at a time.
for i = size(s, 1) - 2:-1:1
ws = size(w);
h = wavecopy('h', cd, s, i);
pad = ws - size(h); frontporch = round(pad / 2);
h = padarray(h, frontporch, fill, 'pre');
h = padarray(h, pad - frontporch, fill, 'post');
v = wavecopy('v', cd, s, i);
pad = ws - size(v); frontporch = round(pad / 2);
v = padarray(v, frontporch, fill, 'pre');
v = padarray(v, pad - frontporch, fill, 'post');
d = wavecopy('d', cd, s, i);
pad = ws - size(d); frontporch = round(pad / 2);
d = padarray(d, frontporch, fill, 'pre');
d = padarray(d, pad - frontporch, fill, 'post');
% Add 1 pixel white border.
switch lower(border)
case 'append'
w = padarray(w, [1 1], 1, 'post');
h = padarray(h, [1 0], 1, 'post');
v = padarray(v, [0 1], 1, 'post');
case 'absorb'
w(:, end) = 1; w(end, :) = 1;
h(end, :) = 1; v(:, end) = 1;
otherwise
error('Unrecognized BORDER parameter.');
end
w = [w h; v d]; % Concatenate coefs.
end
if nargout == 0
imshow(w); % Display result.
end ...
有没有可以参考的用MATLAB神经网络实现图像识别的源代码
水果识别。我以前做过,但不是根据BP神经网络。
你可以根据每一个水果的弧度 面积 色素比等判断出每一个水果。
matlab图像识别
1.识别静态的整个人体较难;即使识别出来结果也不可靠,所以现在主要以手势/人脸识别为主;这是因为手和脸上面有比较独特的特征点。你说的滤波归根结底还是要找出具有灰度跳变的高频部分作为人体;这除非背景中除了人以外没有其他突出的物体;否则光凭滤波二值法检测人体是不太现实。
2 两张图片中人要是产生相对运动,检测起来就容易多了;利用帧间差分找到图像中灰度相差大的部分(你用的滤波也是一种手段);然后二值化区域连通;要是图像中没有其他移动物体计算连通区域的变动方向就是人的运动方向。
你可以去PUDN上搜搜相关的目标检测的代码;完全和你这个对应是不可能的。照你说的情况可以先建立起静态背景的模型(或者直接在没人的时候拍张);然后不断的与这个背景做差,原理和帧间差分一样。建议你先从典型的帧间差分例程开始下手(比如移动车辆的检测,这个比较多)。
你在二值化之后加上一个区域连通的步骤;即使用膨胀或者闭运算;这样你的轮廓就是连续的了;用matlab的话bwlabel可以统计连通区域里面像素的个数也就是人体面积大小。质心就是横竖坐标的平均值;取所有人体点的横竖坐标分别累加;除以坐标总数得到的x和y平均值;这个就是质心了