图片浮雕效果算法
图片浮雕效果算法

浮雕算法公式:
newRgb_R = thisRgb_R - nextRgb_R + 125
newRgb_G = thisRgb_G - nextRgb_G + 125
newRgb_B = thisRgb_B - nextRgb_B + 125
其中:newRgb代表新的rgb值,thisRgb代表当前像素的rgb,nextRgb代表thisRgb像素的相邻像素
在处理浮雕算法过程中,可以选择色值125 为基础色值主要是因为rgb(125,125,125)为灰色, 因为在图片中相邻像素点的颜色值比较接近,只有颜色差异比较大的时候结果才会比较明显, 而其他平滑区域则值都接近125左右,也就是灰色,这样 就具有了浮雕效果。

延伸:通过浮雕效果,可以想像到其它的类似效果,如把基值125换成其它色值,就会出现更多的滤镜效果。

原图如下:

效果图如下:

 

核心代码如下:


@Component(value = "reliefFilter")
public class ReliefFilter extends AbstractPictureFilter {

    /**
     * log
     **/
    private static final Log log = LogFactory.getLog(ReliefFilter.class);

    /**
     * 对像素color 进行处理
     *
     * @param color 原color
     * @return 新color
     */
    @Override
    protected Color filterColor(Color color) {
        return null;
    }

    /**
     * 对图片增加滤镜
     *
     * @param image 图片
     * @return 增加滤镜之后的图片
     */
    @Override
    public BufferedImage pictureAddFilter(BufferedImage image) {

        BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
        for (int i = 0; i < image.getWidth(); i++) {
            for (int j = 0; j < image.getHeight(); j++) {
                //当前像素
                int thisRgb = image.getRGB(i, j);
                //相邻像素
                int nextRgb;
                if(i == image.getWidth()-1){
                    nextRgb = image.getRGB(i, j);
                }else{
                    nextRgb = image.getRGB(i+1, j);
                }
                Color thisColor = new Color(thisRgb);
                Color nextColor = new Color(nextRgb);
                Color newColor = new Color(
                        color((thisColor.getRed() - nextColor.getRed())+125),
                        color((thisColor.getGreen() - nextColor.getGreen())+125),
                        color((thisColor.getBlue() - nextColor.getBlue())+125)
                        );
                newImage.setRGB(i,j,newColor.getRGB());
            }
        }
        return newImage;
    }

    //防止像素值大于255 或小于0
    private int color(int color) {
        if (color > 255 || color < 0) {
            return 125;
        }
        return color;
    }
}
Copyright © 2019-2020 2024-04-26 16:49:24