对图像处理的过程中会遇到一些场景需要将图片反色,反色就是取像素的互补色,比如当前像素是0X00FFFF,对其取反色就是0XFFFFFF – 0X00FFFF = 0XFF0000,依次对图像中的每个像素这样做,最后得到的就是原始图像的反色。
一个对图像取反色的例子:
package bar.ocr; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class Main_005 { public static void main(String[] args) { inverseColor("D:\test\ocr\binary_process\woman.jpg", "D:\test\ocr\binary_process\womaninverseColor.jpg"); } public static BufferedImage inverseColor(BufferedImage bufferedImage){ int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for(int i=0; i<width; i++){ for(int j=0; j<height; j++){ int rgb = bufferedImage.getRGB(i, j); resultImage.setRGB(i, j, 0XFFFFFF - rgb); } } return resultImage; } public static boolean inverseColor(String src, String dest){ BufferedImage srcImage = null; try { srcImage = ImageIO.read(new File(src)); } catch (IOException e) { e.printStackTrace(); } if(srcImage==null){ return false; } BufferedImage destImage = inverseColor(srcImage); String extension = dest.substring(dest.lastIndexOf(".")+1); try { return ImageIO.write(destImage, extension, new File(dest)); } catch (IOException e) { e.printStackTrace(); } return false; } }
反色之前:
反色之后:
.