前言
仅仅是记录与分享自己在学习过程中遇到的问题与解决办法,可能有一些错误的观点或理解等,如果有说错的地方麻烦请大家指正,谢谢。该代码仅仅是从rgb角度进行操作,没有使用opencv等第三方库。
灰度处理
灰度处理其实是将图片的rgb值变为相同的值,当r=g=b=255的时候则为白色,r=g=b=0的时候则为黑色。由此我们可以将灰度值分为256级,即0~255。
所以只要在处理的时候能把图片的rgb值都赋予相同的值我们就能称之为灰度处理后的图片。
有如下几种灰度处理的方法:
1.任取rgb中的任一值作为灰度值,个人理解是用于专项处理某一突出色彩时所用。
2.取rgb中的最大值作为灰度值。
3.取rgb的值的平均值作为灰度值。
4.加权取灰度值
我们重点讲讲最后一种方法。由于人眼对绿色的敏感最高, 对蓝色敏感最低,因此,按下式对RGB三分量进行加权平均能得到较合理的灰度图像。
gray=0.3*r+0.59*g+0.11*b;
我们来看下效果图
这是一张毛衣图片处理前:
我们用灰度方法处理后的效果分别如下:
1.依次是取red,green,blue所得到的效果
可以看到色差还是比较明显的。接下来我们贴出代码,这部分难度不是很大,大家可以自己优化一下。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GrayDeal
{
BufferedImage bufferedImage;
int height;
int width;
public GrayDeal(String path)
{
try
{
bufferedImage = ImageIO.read(new File(path));
height = bufferedImage.getHeight();
width = bufferedImage.getWidth();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void Deal()
{
Color color;
for(int y = 0;y < height;y++)
{
for(int x = 0;x < width;x++)
{
color = new Color(bufferedImage.getRGB(x,y));
int gray = color.getRed();//此处用r,g,b的值当作灰度值
//int gray = color.getGreen();
//int gray = color.getBlue();
color = new Color(gray,gray,gray);
bufferedImage.setRGB(x,y,color.getRGB());
}
}
}
public void outPicture(String path)
{
try
{
ImageIO.write(bufferedImage,"png",new File(path));
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
GrayDeal gd = new GrayDeal("图片/2.png");
gd.Deal();
gd.outPicture("图片/Red.png");
}
}
2.取各像素点的rgb值中的最值为灰度值,分别是最大值和最小值
其它部分如上,只需要修改个Deal部分即可
public void Deal()
{
Color color;
for(int y = 0;y < height;y++)
{
for(int x = 0;x < width;x++)
{
color = new Color(bufferedImage.getRGB(x,y));
int r = color.getRed();
int g = color.getGreen();
//int gray = Math.max(r,g);
int gray = Math.min(r,g);
int b = color.getBlue();
//gray = Math.max(gray,b);//此处将r,g,b的值进行比较取最值
gray = Math.min(gray,b);
color = new Color(gray,gray,gray);
bufferedImage.setRGB(x,y,color.getRGB());
}
}
}
3.即求出rgb后得出gray=(r+g+b)/3,效果如下:
代码同上:
public void Deal()
{
Color color;
for(int y = 0;y < height;y++)
{
for(int x = 0;x < width;x++)
{
color = new Color(bufferedImage.getRGB(x,y));
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
int gray = (r+g+b)/3;//此处将r,g,b的值相加取平均
color = new Color(gray,gray,gray);
bufferedImage.setRGB(x,y,color.getRGB());
}
}
}
4.用灰度公式求,gray = 0.3*r+0.59*g+0.11*b,效果如下:
代码同上:
public void Deal()
{
Color color;
for(int y = 0;y < height;y++)
{
for(int x = 0;x < width;x++)
{
color = new Color(bufferedImage.getRGB(x,y));
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
int gray = (int)(0.3*r + 0.59*g + 0.11*b);//此处将r,g,b的值相加取平均
color = new Color(gray,gray,gray);
bufferedImage.setRGB(x,y,color.getRGB());
}
}
}