Search code examples
javaopencvimage-processingopencv3.0javacv

Trying to change color of a small png image using OpenCV (Java)


Here I am using OpenCV lib with java to change the transparent part as White and the shapes inside on it to black color and little thick. I tried to use cvtColor(img, hsv, Imgproc.COLOR_BGR2GRAY); but the whole image changed to gray. I need help with this

Here is the Original image Which i need to change color

image

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String img_url1 = "C:\\\\Users\\\\me\\\\Desktop\\\\cpt\\\\1.png";
Mat img = Imgcodecs.imread(img_url1);
if( img.empty() ) {
    System.out.println("Error opening image!");
    System.out.println("Program Arguments: [image_name -- default ../data/lena.jpg] \n");
    System.exit(-1);
}


Mat hsv = new Mat();
Imgproc.cvtColor(img, hsv, Imgproc.COLOR_BGR2GRAY);

Imgcodecs.imwrite("C:\\\\Users\\\\me\\\\Desktop\\\\cpt\\\\1-cpy.png", hsv);

Outupt image after processing:

image


Solution

  • This is a C++ code but you can easily convert it to JAVA.

      Mat img = imread("image.png",-1);
    
      //split channels, extract 3rd channel
      std::vector<Mat> channels;
      split(img, channels);
    
      // convert to white background and black foreground
      Mat black;
      bitwise_not(channels.at(3), black);
    
    
      imshow("image", black);
      waitKey(0);
    

    result