📌  相关文章
📜  Java中的图像处理——彩色图像到负图像的转换

📅  最后修改于: 2022-05-13 01:55:39.861000             🧑  作者: Mango

Java中的图像处理——彩色图像到负图像的转换

先决条件:

  • Java中的图像处理——读写
  • Java中的图像处理——获取和设置像素
  • Java中的图像处理——彩色图像到灰度图像的转换

在这组中,我们将彩色图像转换为负片图像。

彩色图像(RGB 颜色模型)– RGB 颜色模型是一种加色混合模型,其中红光、绿光和蓝光以各种方式叠加在一起,以再现各种颜色。

负像 -负像是完全倒置的,其中亮区显得暗,反之亦然。负片彩色图像另外颜色反转,红色区域呈现青色,绿色呈现洋红色,蓝色呈现黄色,反之亦然。

图像负片是通过从最大强度值中减去每个像素来产生的。例如,在 8 位灰度图像中,最大强度值为 255,因此从 255 中减去每个像素以生成输出图像。

算法:

  1. 获取像素的 RGB 值。
  2. 计算新的 RGB 值如下:
    • R = 255 - R
    • G = 255 – G
    • B = 255 – B
  3. 将像素的 R、G 和 B 值替换为步骤 2 中计算的值。
  4. 对图像的每个像素重复步骤 1 到步骤 3。

执行:

Java
// Java program to demonstrate
// colored to negative conversion
  
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
  
public class Negative {
    public static void main(String args[])
        throws IOException
    {
        BufferedImage img = null;
        File f = null;
  
        // read image
        try {
            f = new File(
                "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png");
            img = ImageIO.read(f);
        }
        catch (IOException e) {
            System.out.println(e);
        }
  
        // Get image width and height
        int width = img.getWidth();
        int height = img.getHeight();
  
        // Convert to negative
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int p = img.getRGB(x, y);
                int a = (p >> 24) & 0xff;
                int r = (p >> 16) & 0xff;
                int g = (p >> 8) & 0xff;
                int b = p & 0xff;
  
                // subtract RGB from 255
                r = 255 - r;
                g = 255 - g;
                b = 255 - b;
  
                // set new RGB value
                p = (a << 24) | (r << 16) | (g << 8) | b;
                img.setRGB(x, y, p);
            }
        }
  
        // write image
        try {
            f = new File(
                "C:/Users/hp/Desktop/Image Processing in Java/GFG.png");
            ImageIO.write(img, "png", f);
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
}


输出 -