将负片图像转换为正片

时间:2011-12-28 23:14:07

标签: java c++ image

我已将旧的底片扫描到我的电脑上。我想写一个小程序将负图像转换为正状态。

我知道有几个图像编辑器应用程序,我可以使用它来实现这种转换,但我正在研究如何操作像素以通过一个小应用程序自己转换它们。

有人能给我一个良好的开端吗?如果可能的话,示例代码也将非常受欢迎。

3 个答案:

答案 0 :(得分:29)

我刚刚写了一个实例。给定以下输入图像img.png

img.png

输出将是新图像invert-img.png,如

invert-img.png

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

class Convert
{
    public static void main(String[] args)
    {
        invertImage("img.png");
    }

    public static void invertImage(String imageName) {
        BufferedImage inputFile = null;
        try {
            inputFile = ImageIO.read(new File(imageName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (int x = 0; x < inputFile.getWidth(); x++) {
            for (int y = 0; y < inputFile.getHeight(); y++) {
                int rgba = inputFile.getRGB(x, y);
                Color col = new Color(rgba, true);
                col = new Color(255 - col.getRed(),
                                255 - col.getGreen(),
                                255 - col.getBlue());
                inputFile.setRGB(x, y, col.getRGB());
            }
        }

        try {
            File outputFile = new File("invert-"+imageName);
            ImageIO.write(inputFile, "png", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果要创建单色图像,可以将col的计算更改为以下内容:

int MONO_THRESHOLD = 368;
if (col.getRed() + col.getGreen() + col.getBlue() > MONO_THRESHOLD)
    col = new Color(255, 255, 255);
else
    col = new Color(0, 0, 0);

以上将为您提供以下图片

monochromic-img.png

您可以调整MONO_THRESHOLD以获得更令人满意的输出。增加数字会使像素变暗,反之亦然。

答案 1 :(得分:4)

试试LookupOp。这是来自Filthy Rich Clients的sample一书。

答案 2 :(得分:2)

然后开始吧。假设您可以访问负片图像中的每个像素,并且每个像素都有RGB分量,请获取原始像素的RGB分量,如下所示:

int originalRed   = Math.abs( pixel.getRed( ) - 255 );
int originalGreen = Math.abs( pixel.getGreen( ) - 255 );
int originalBlue  = Math.abs( pixel.getBlue( ) - 255 );
// now build the original pixel using the RGB components

对每个像素执行上述操作,您可以通过逐个像素重新创建原始图像来获取原始图像。