Reputation: 23
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
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:
Upvotes: 2
Views: 1698
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
Reputation: 18331
(1) Read the
PNG
withAlpha channel
with the flagIMREAD_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:
Alpha:
Upvotes: 1
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);
Upvotes: 0