Greeny Clicks
Greeny Clicks

Reputation: 23

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

Upvotes: 2

Views: 1698

Answers (3)

Greeny Clicks
Greeny Clicks

Reputation: 23

I have just figured out it with the help of @zindarod answer, here is the solution

         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         String img_url1 = "C:\\\\Users\\\\me\\\\Desktop\\\\cpt\\\\1.png";
         Mat img = Imgcodecs.imread(img_url1, -1);


         List<Mat> channels = new ArrayList<>();
         Core.split(img, channels);

         Mat black = new Mat();
         Core.bitwise_not(channels.get(3), black);

         String file2 = "C:\\\\\\\\Users\\\\\\\\me\\\\\\\\Desktop\\\\\\\\cpt\\\\\\\\1-cpy.png"; 
         Imgcodecs.imwrite(file2, black);

Upvotes: 0

Kinght 金
Kinght 金

Reputation: 18331

(1) Read the PNG with Alpha channel with the flag IMREAD_UNCHANGED.

(2) Then Split the channels and get the alpha.

(3) Other steps ...

import java.util.*;
import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;

public class xtmp{
    public static void main(String[] args){
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        test();
    }
    static void test(){
        // Read with alpha channel 
        Mat img = Imgcodecs.imread("transparent.png", Imgcodecs.IMREAD_UNCHANGED);
        // Split the channels and get the alpha 
        List<Mat> bgra = new ArrayList<Mat>(4);
        Core.split(img, bgra) ;
        // Save 
        Mat alpha = bgra.get(3);
        Imgcodecs.imwrite("alpha.png", alpha);
    }
}

Transparent:

enter image description here

Alpha:

enter image description here

Upvotes: 1

zindarod
zindarod

Reputation: 6468

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

Upvotes: 0

Related Questions