简体   繁体   English

如何在Java中改进反转+灰度运算符?

[英]How to improve invert + grayscale operator in Java?

I want to invert and gray scale an image. 我想反转和灰度图像。 Here is my original image: 这是我原来的形象:
在此输入图像描述

Here is the final result I want to achieve (produced with Paint.NET): 这是我想要实现的最终结果(使用Paint.NET生成):
在此输入图像描述

However using some (basic?) Java code found on Internet, I only get the picture below: 但是使用在Internet上找到的一些(基本?)Java代码,我只能得到如下图: 在此输入图像描述

Here is the code I used: 这是我使用的代码:

private static final byte[] invertTable;

static {
    invertTable = new byte[256];
    for (int i = 0; i < 256; i++) {
        invertTable[i] = (byte) (255 - i);
    }
}

private static BufferedImage grayScale(BufferedImage source) {
    ColorConvertOp grayScale = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);

    return grayScale.filter(source,null);
}

private static BufferedImage invertImage(final BufferedImage src) {
    final int w = src.getWidth();

    final int h = src.getHeight();

    final BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

    final BufferedImageOp invertOp = new LookupOp(new ByteLookupTable(0, invertTable), null);

    return invertOp.filter(src, dst);
}

// ...
BufferedImage sourceImage = ...
BufferedImage convertedImage = grayScale(invertImage(sourceImage));

How can I improve the above code? 如何改进上述代码?

Using Imgproc and Core , I did 使用ImgprocCore ,我做到了

Mat src = new Mat();
Mat gray = new Mat();
src = Highgui.imread("...");
Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
Core.bitwise_not(gray, gray);
Highgui.imwrite("...", gray);

and got something closer, though not identical: 并得到更接近的东西,虽然不相同:

OpenCV默认灰度映射+按位反转

In the title it says OpenCV but there's a tag for BoofCV. 在标题中它表示OpenCV,但有一个标签为BoofCV。 So here's how to do it in BoofCV: 所以这是在BoofCV中如何做到这一点:

BufferedImage orig = UtilImageIO.loadImage("filename");
ImageUInt8 gray = ConvertBufferedImage.convertFrom(orig, (ImageUInt8) null);
ImageUInt8 inverted = new ImageUInt8(gray.width,gray.height);
GrayImageOps.invert(gray,255,inverted);

在此输入图像描述

While I'm not familiar with ColorConvertOp, I would suspect that it is converting the color image to greyscale in a different way then Paint.NET is. 虽然我不熟悉ColorConvertOp,但我怀疑它是以与Paint.NET不同的方式将彩色图像转换为灰度。 There is no correct way. 没有正确的方法。

Take a look at the yellow. 看看黄色。 Should yellow be a dark or light grey? 黄色应该是深色还是浅灰色? It looks like Paint.NET thinks it is light and the ColorConvertOp thinks it is dark. 看起来Paint.NET认为它很轻,ColorConvertOp认为它很暗。

Try doing the conversion yourself by just averaging the red/green/blue. 尝试通过平均红色/绿色/蓝色来自己进行转换。

(red+green+blue)/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM