bytedeco / javacv

Java interface to OpenCV, FFmpeg, and more
Other
7.56k stars 1.58k forks source link

Wrong colors when using Java2DFrameUtils to convert BufferedImage to Mat #1323

Closed waicool20 closed 4 years ago

waicool20 commented 4 years ago

I'm trying to use Java2DFrameUtils class to convert my BufferedImage to Mat but it seems the R and B channel get mixed up in certain cases and I'm not able to assert what factor comes to play since some images show up just fine while others don't. I've checked the image properties through gimp and don't seem to see any problems between the cases.

I wrote this in kotlin hope you don't mind, the images here are random ones I found laying around as well.

import org.bytedeco.javacv.Java2DFrameUtils
import org.bytedeco.opencv.global.opencv_highgui
import java.io.File
import javax.imageio.ImageIO

fun main() {
    val image = ImageIO.read(File("Vim Cheat Sheet.png"))
    val imageMat = Java2DFrameUtils.toMat(image)

    opencv_highgui.imshow("Test", imageMat)
    opencv_highgui.waitKey()
}

Here's the original image: Vim Cheat Sheet

And this is what shows up: image


Another example: calculator image


This one works fine somehow World Of Warships Iowa Class BB Missouri

image


And of course bytedeco image

saudet commented 4 years ago

You need to invert the R and B channels. To do that easily, we can set the flipChannels argument of Java2DFrameConverter.getBufferedImage() and/or Java2DFrameConverter.getFrame() to true.

saudet commented 4 years ago

Duplicate of #1053

saudet commented 4 years ago

As to why it sometimes happens and sometimes doesn't, that's just how ImageIO and OpenCV work. You can refer to issues #181 and #1075 for additional information about this.