这个是个人实现的对于纯色图片的二分类,纯色图片就是指只有一种颜色的图片,首先使用red文件夹中的4张图片和blue文件夹中的5张图片尝试训练出感知机的参数w,b,然后读取新的图片,判断红色还是蓝色
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.*;
class Myimg{
public int r=0,g=0,b=0;
public int cate=0;
Myimg(int rr,int gg,int bb,int cater)
{
r=rr;
g=gg;
b=bb;
cate=cater;
}
}
public class Perceptron_image{
Myimg mg[]=new Myimg[9];
int mgcnt=0;
int w1=0,w2=0,w3=0,m=0;
void createRGB(String path,int flag)
{
String imgPath = path;
try{
BufferedImage src = ImageIO.read(new FileInputStream(imgPath));
//BufferedImage src=new BufferedImage("C:\\Users\\Administrator\\Desktop\\blue1.jpg");
int width = src.getWidth();
int height = src.getHeight();
int[] inPixels = new int[width*height];
src.getRGB( 0, 0, width, height, inPixels, 0, width );
int r=0,g=0,b=0;
for(int rgb:inPixels)
{
r=(rgb>>16)&0xff;
g=(rgb>>8)&0xff;
b=(rgb)&0xff;
//System.out.println(r+" "+g+" "+b);
}
mg[mgcnt]=new Myimg(r,g,b,flag);
mgcnt++;
}
catch(Exception e)
{}
}
void testRGB(String path)
{
String imgPath = path;
try{
BufferedImage src = ImageIO.read(new FileInputStream(imgPath));
int width = src.getWidth();
int height = src.getHeight();
int[] inPixels = new int[width*height];
src.getRGB( 0, 0, width, height, inPixels, 0, width );
int r=0,g=0,b=0;
for(int rgb:inPixels)
{
r=(rgb>>16)&0xff;
g=(rgb>>8)&0xff;
b=(rgb)&0xff;
//System.out.println(r+" "+g+" "+b);
}
int res=w1*r+w2*g+w3*b+m;
res=sign(res);
if(res==1)
System.out.println("this is blue!!!!");
else
System.out.println("this is red!!!!");
}
catch(Exception e)
{
}
}
void readimg()
{
String bluepath="C:\\Users\\Administrator\\Desktop\\blue";
for(int i=1;i<=5;i++)
{
String temp=bluepath+"\\blue"+i+".jpg";
createRGB(temp,1);
}
String redpath="C:\\Users\\Administrator\\Desktop\\red";
for(int i=1;i<=4;i++)
{
String temp=redpath+"\\red"+i+".jpg";
createRGB(temp,-1);
}
}
int sign(int x)
{
if(x>0)
return 1;
else if(x<0)
return -1;
else
return 0;
}
void train()
{
while(true)
{
boolean jump=false;
for(int i=0;i<9;i++)
{
int r=mg[i].r;
int g=mg[i].g;
int b=mg[i].b;
int cate=mg[i].cate;
if(sign(r*w1+g*w2+b*w3+m)!=cate)
{
jump=true;
w1=w1+cate*r;
w2=w2+cate*g;
w3=w3+cate*b;
m=m+cate;
break;
}
}
if(jump==false)
{
break;
}
}
System.out.println(w1+" "+w2+" "+w3+" "+m);
}
void test()
{
String path="C:\\Users\\Administrator\\Desktop\\test.jpg";
testRGB(path);
}
public static void main(String[]args)
{
Perceptron_image pi=new Perceptron_image();
pi.readimg();
pi.train();
pi.test();
}
}