将两个图片合并很容易(下面第二个程序是利用Java合并两张图片),但有时候需要从两个合并的图片中分离出一张图片,查了一下OpenCV提供了图片相减的功能,其实不止图片相减,基本的运算opencv都提供了,这里以图片相减为例说明。
- package swing_interface;
- import org.opencv.core.Core;
- import org.opencv.core.CvType;
- import org.opencv.core.Mat;
- import org.opencv.highgui.Highgui;
- /**
- * 执行两个图片的相减操作,用于抓取用户所画的部分,去除本来就有的部分
- */
- public class ImageSub {
- public static void sub(String two_path, String one_path, String des_path) {
- System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
- // 读取图像,不改变图像的原始信息
- Mat image1 = Highgui.imread(two_path, Highgui.CV_LOAD_IMAGE_COLOR);
- Mat image2 = Highgui.imread(one_path, Highgui.CV_LOAD_IMAGE_COLOR);
- Mat image3 = new Mat(image1.size(), CvType.CV_64F);
- Core.subtract(image2, image1, image3);
- Mat image5 = new Mat(image1.size(), CvType.CV_64F);
- Core.bitwise_not(image3, image5);
- Highgui.imwrite(des_path, image5);
- }
- public static void main(String[] args) {
- String dir = System.getProperty("user.dir");
- ImageSub.sub(dir+"/r_pic/user_paint_two.jpg", dir+"/r_pic/user_paint_one.jpg", dir+"/res.jpg");
- }
- }
另外附上用java合并两张图片的程序,当然用opencv实现起来更方便。
- package merge;
- import java.awt.Graphics2D;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- /**
- * 图片拼接
- * 把多张宽度一样的图片拼接成一张大图片
- */
- public class Merge {
- public static String path = System.getProperty("user.dir");
- public static void main(String[] args) {
- callMergeSimple();
- }
- public static void callMergeSimple(){
- File file1 = new File(path+"/merge1/1.jpg");
- File file2 = new File(path+"/merge1/2.jpg");
- File file3 = new File(path+"/merge2/res.jpg");
- BufferedImage image1 = null,image2 = null;
- try {
- image1 = ImageIO.read(file1);
- image2 = ImageIO.read(file2);
- } catch (IOException e) {
- e.printStackTrace();
- }
- mergeSimple(image1,image2,100,300,file3);
- }
- public static boolean mergeSimple(BufferedImage image1, BufferedImage image2, int posw, int posh, File fileOutput) {
- //合并两个图像
- int w1 = image1.getWidth();
- int h1 = image1.getHeight();
- int w2 = image2.getWidth();
- int h2 = image2.getHeight();
- BufferedImage imageSaved = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g2d = imageSaved.createGraphics();
- g2d.drawImage(image1, null, 0, 0);
- for (int i = 0; i < w2; i++) {
- for (int j = 0; j < h2; j++) {
- int rgb1 = image1.getRGB(i + posw, j + posh);
- int rgb2 = image2.getRGB(i, j);
- if (rgb1 != rgb2) {
- rgb2 = rgb1 & rgb2;
- }
- imageSaved.setRGB(i + posw, j + posh, rgb2);
- }
- }
- boolean b = false;
- try {
- b = ImageIO.write(imageSaved, "png", fileOutput);
- } catch (IOException ie) {
- ie.printStackTrace();
- }
- return b;
- }
- }