如何使用Java OpenCV库将负片转换为正片?


要将负片转换为正片 -

  • 使用 ImageIO.read() 方法读取所需的图像。

  • 获取图像的高度和宽度。

  • 使用嵌套的 for 循环遍历图像中的每个像素。

  • 使用 getRGB() 方法获取像素值。

  • 要从像素中检索每个值,您需要将其右移到每种颜色的起始位置,即 alpha 为 24,红色为 16 等,并执行与 0Xff 的按位与运算。这会掩盖变量,保留最后 8 位并忽略所有其余位。

  • 通过从 255 中减去它们来计算新的红色、绿色和蓝色值。

  • 通过将其各自位置向左移动 ARGB 来重建像素,并使用按位或将它们连接起来。

  • 使用 setRGB() 方法设置新的像素值。

示例

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Negative2Color {
   public static void main(String args[])throws IOException {
      //Reading the image
      File file= new File("D:\Images\cat_neg.jpg");
      BufferedImage img = ImageIO.read(file);
      for (int y = 0; y < img.getHeight(); y++) {
         for (int x = 0; x < img.getWidth(); x++) {
            //Retrieving contents of a pixel
            int p = img.getRGB(x,y);
            //Getting the A R G B values from the pixel value
            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);
         }
      }
      //Saving the modified image
      file = new File("D:\Images\negative_positive.jpg");
      ImageIO.write(img, "jpg", file);
      System.out.println("Done...");
   }
}

输入

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

更新于: 2020年4月9日

458 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告