Java Code Examples for org.opencv.imgcodecs.Imgcodecs#imwrite()

The following examples show how to use org.opencv.imgcodecs.Imgcodecs#imwrite() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Element.java    From SikuliNG with MIT License 6 votes vote down vote up
public String save(URL url, String name) {
  if (!hasContent()) {
    load();
  }
  urlImg = null;
  if (SX.isNotNull(url) && hasContent()) {
    if ("file".equals(url.getProtocol())) {
      log.trace("save: %s", url);
      String imgFileName = Content.asImageFilename(url.getPath());
      Mat imgContent = getContent();
      boolean imwrite = Imgcodecs.imwrite(imgFileName, imgContent);
      if (imwrite) {
        urlImg = url;
        setName(name);
        return imgFileName;
      } else {
        log.error("save: Imgcodecs.imwrite no success: (%s) %s", imgContent, imgFileName);
      }
    } else {
      //TODO save: http and jar
      log.error("save: not implemented: %s", url);
    }
  }
  return "";
}
 
Example 2
Source File: OpenCVoperation.java    From Human-hair-detection with Apache License 2.0 6 votes vote down vote up
public void testGrabCut()
{
    sourceImage = Imgcodecs.imread(resultDirectory+fileName,Imgcodecs.CV_LOAD_IMAGE_COLOR);
    System.out.println("result Directory is: "+ resultDirectory+fileName);
    
    Mat result = new Mat(sourceImage.size(),sourceImage.type());
    Mat bgModel = new Mat();    //background model
    Mat fgModel = new Mat();    //foreground model
    
    //draw a rectangle 
    Rect rectangle = new Rect(1,1,sourceImage.cols()-1,sourceImage.rows()-1);
    
    Imgproc.grabCut(sourceImage, result,rectangle, bgModel,fgModel,10,Imgproc.GC_INIT_WITH_RECT);  
    Core.compare(result,new Scalar(3,3,3),result,Core.CMP_EQ);
    matrix2_grabcut = new Mat(sourceImage.size(),CvType.CV_8UC3,new Scalar(255,255,255));
    sourceImage.copyTo(matrix2_grabcut, result);
    
    Imgcodecs.imwrite(resultDirectory+grabcutOutput,matrix2_grabcut);
    
   // displayPixels(matrix2_grabcut);
}
 
Example 3
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 6 votes vote down vote up
/**
 * Detects faces in an image, draws boxes around them, and writes the results
 * @param fileName
 * @param destName
 */
public static void drawRect(String fileName, String destName){
    Mat image = Imgcodecs.imread(fileName);
    // Create a face detector from the cascade file in the resources
    // directory.
    CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml");
    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);
    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width,
                rect.y + rect.height), new Scalar(0, 255, 0));
    }

    Imgcodecs.imwrite(destName, image);

}
 
Example 4
Source File: OpenCVNonMavenExamples.java    From Java-for-Data-Science with MIT License 6 votes vote down vote up
public static void denoise() {
        String imgInPath = "captchaExample.jpg";
        imgInPath = "MyCaptcha.PNG";
        imgInPath = "blurredtext.jpg";
        String imgOutPath = "captchaNoiseRemovedExample.png";
        imgOutPath = "MyNoiseRemovedCaptcha.PNG";

        Mat image = Imgcodecs.imread(imgInPath);
        Mat out = new Mat();
        Mat tmp = new Mat();
        Mat kernel = new Mat(new Size(3, 3), CvType.CV_8UC1, new Scalar(255));
//        Mat kernel = new Mat(image.size(), CvType.CV_8UC1, new Scalar(255));
        Imgproc.morphologyEx(image, tmp, Imgproc.MORPH_OPEN, kernel);
        Imgproc.morphologyEx(tmp, out, Imgproc.MORPH_CLOSE, kernel);
        Imgcodecs.imwrite(imgOutPath, out);
    }
 
Example 5
Source File: OpenCVoperation.java    From Human-hair-detection with Apache License 2.0 6 votes vote down vote up
public void predict_hair_color()
{
    Mat hsv_input = matrix9_finalOutput.clone();
    List<Mat> channels= new ArrayList<>();
    Mat hsv_histogram = new Mat();
    MatOfFloat  ranges = new MatOfFloat(0,180);
    MatOfInt histSize = new MatOfInt(255);
    Imgproc.cvtColor(hsv_input, hsv_input, Imgproc.COLOR_BGR2HSV);
    Core.split(hsv_input, channels);
    Imgproc.calcHist(channels.subList(0,1), new MatOfInt(0), new Mat(), hsv_histogram, histSize, ranges);
    int hist_w =256;
    int hist_h = 150;
    
    int bin_w =(int)Math.round(hist_w/histSize.get(0,0)[0]);
    Mat histImage= new Mat(hist_h,hist_w,CvType.CV_8UC3,new Scalar(0,0,0));
    
    for(int i=1;i < histSize.get(0,0)[0];i++)
    {
        Imgproc.line(histImage, new Point(bin_w * (i - 1), hist_h - Math.round(hsv_histogram.get(i - 1, 0)[0])), new Point(bin_w * (i), hist_h - Math.round(hsv_histogram.get(i, 0)[0])), new Scalar(255,0,0),2);			    
    }
    Imgcodecs.imwrite(resultDirectory+"histogram_image.png",histImage);
}
 
Example 6
Source File: DetectObjectTest.java    From classchecks with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetectManyObject() {
	String opencvDLL = "G:/java/JavaProjectRelease/classchecks/src/main/webapp/WEB-INF/dll/x64/opencv_java320.dll";
	System.load(opencvDLL);
	
	String haarcascade = "haarcascade_frontalface_alt.xml";
	
	
	CascadeClassifier cascade = new CascadeClassifier(XMLFilePath + haarcascade);
	
	Mat src = Imgcodecs.imread(imageDir + "/split/14.jpg");
	
	MatOfRect objects = new MatOfRect();
	int scaledWidth = src.width();
	
	DetectObject.detectManyObject(src, cascade, objects, scaledWidth);
	
	Rect [] rects = objects.toArray();
	int i = 0;
	for(Rect r : rects) {
		/*Imgproc.rectangle(src, new Point(r.x-100 , r.y-100 ), 
				new Point(r.x + r.width + 80, 
						r.y + r.height + 80), new Scalar(0, 0, 255), 3);*/
		Imgproc.rectangle(src, r.tl(), 
				r.br(), new Scalar(0, 0, 255), 3);
		/*r.width += 120;
		r.height += 120;
		r.x -= 100;
		r.y -= 100;
		System.out.println(r);
		Mat roi = new Mat(src, r);
		Imgcodecs.imwrite("e:/classchecks/2017417/split/"+i+".jpg", roi);
		i ++;*/
	}
	Imgcodecs.imwrite("e:/classchecks/2017417/dectctManyObject.jpg", src);
	//Imgcodecs.imwrite("e:/classchecks/dectctManyObject.jpg", src);
}
 
Example 7
Source File: VideoMotionDetector.java    From video-stream-analytics with Apache License 2.0 5 votes vote down vote up
private static void saveImage(Mat mat,VideoEventData ed,String outputDir){
	String imagePath = outputDir+ed.getCameraId()+"-T-"+ed.getTimestamp().getTime()+".png";
	logger.warn("Saving images to "+imagePath);
	boolean result = Imgcodecs.imwrite(imagePath, mat);
	if(!result){
		logger.error("Couldn't save images to path "+outputDir+".Please check if this path exists. This is configured in processed.output.dir key of property file.");
	}
}
 
Example 8
Source File: OpenCVNonMavenExamples.java    From Java-for-Data-Science with MIT License 5 votes vote down vote up
public void noiseRemoval() {
//        Mat Kernel = cv::Mat(cv::Size(Maximum_Width_of_Noise,Maximum_Height_of_noise),CV_8UC1,cv::Scalar(255));        
        Mat Kernel = new Mat(new Size(3, 3), CvType.CV_8U, new Scalar(255));
        Mat source = Imgcodecs.imread("noiseExample.png");
        Mat temp = new Mat();
        Mat topHat = new Mat();
        Mat destination = new Mat();

        Imgproc.morphologyEx(source, temp, Imgproc.MORPH_OPEN, Kernel);
        Imgproc.morphologyEx(temp, destination, Imgproc.MORPH_CLOSE, Kernel);
//        Imgproc.morphologyEx(temp, topHat, Imgproc.MORPH_GRADIENT, Kernel);
//        Imgproc.morphologyEx(topHat, destination, Imgproc.MORPH_CLOSE, Kernel);
        Imgcodecs.imwrite("noiseRemovedExample.png", source);
    }
 
Example 9
Source File: OpenCVNonMavenExamples.java    From Java-for-Data-Science with MIT License 5 votes vote down vote up
public void convertImage() {
    Mat source = Imgcodecs.imread("cat.jpg");
    // The extension determines the format
    Imgcodecs.imwrite("convertedCat.jpg", source);
    Imgcodecs.imwrite("convertedCat.jpeg", source);
    Imgcodecs.imwrite("convertedCat.webp", source);
    Imgcodecs.imwrite("convertedCat.png", source);
    Imgcodecs.imwrite("convertedCat.tiff", source);
}
 
Example 10
Source File: OpenCVNonMavenExamples.java    From Java-for-Data-Science with MIT License 5 votes vote down vote up
public void enhanceImageBrightness() {
    double alpha = 1;   // Change to 2 for more brightness
    double beta = 50;
    String fileName = "cat.jpg";

    Mat source = Imgcodecs.imread("cat.jpg");
    Mat destination = new Mat(source.rows(), source.cols(),
            source.type());
    source.convertTo(destination, -1, 1, 50);
    Imgcodecs.imwrite("brighterCat.jpg", destination);
}
 
Example 11
Source File: ImageProcessor.java    From video-stream-classification with Apache License 2.0 5 votes vote down vote up
private static void saveImageAndData(Mat mat, VideoEventData ed, String match, String outputDir) throws IOException{
	String imagePath = outputDir+ed.getCameraId()+"-T-"+ed.getTimestamp().getTime()+".jpg";
	logger.warn("Saving images to "+imagePath);
	boolean result = Imgcodecs.imwrite(imagePath, mat);
	if(!result){
		logger.error("Couldn't save images to path "+outputDir+".Please check if this path exists. This is configured in processed.output.dir key of property file.");
	}
	String matchPath = outputDir+ed.getCameraId()+"-T-"+ed.getTimestamp().getTime()+".txt";
	logger.warn("Saving classification result to "+imagePath);
	Files.write(Paths.get(matchPath), match.getBytes());
}
 
Example 12
Source File: ImageTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSift1() {
	System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	
	Mat src = Imgcodecs.imread("g:/test/find-src.jpg");
	Mat dst = Imgcodecs.imread("g:/test/find-dest.jpg");
	
	MatOfRect mr = getFace(dst);
	Mat sub = dst.submat(mr.toArray()[0]);
	
	Imgcodecs.imwrite("g:/test/sift-result.jpg", FeatureSiftLannbased(src.t(), sub));
}
 
Example 13
Source File: FixedPredictionTest.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testOnPredictionInterpretation() throws IOException, ClassNotFoundException {
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, appContext, mLoaderCallback);
    YoloV3Classifier detector = (YoloV3Classifier) YoloV3Classifier.create(
            appContext.getAssets(),
            YOLO_MODEL_FILE,
            YOLO_INPUT_SIZE,
            YOLO_INPUT_NAME,
            YOLO_OUTPUT_NAMES,
            YOLO_BLOCK_SIZE,
            1);

    float[][] deserialize = deserialize();

    Bitmap loadedImage = loadFirstImage();
    Bitmap redimBitmap = Bitmap.createScaledBitmap(loadedImage, YOLO_INPUT_SIZE, YOLO_INPUT_SIZE, false);
    ArrayList<Classifier.Recognition> recognitions = detector.debugAndTestpopulateRecognitions(deserialize, redimBitmap);

    Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
    ImageProcessor processor = new ImageProcessor(testContext, detector.getLabels());
    processor.loadImage(loadedImage, YOLO_INPUT_SIZE, YOLO_INPUT_SIZE);
    Mat mat = processor.drawBoxes(recognitions, 0);
    Mat ultimate = new Mat();
    Imgproc.cvtColor(mat, ultimate, Imgproc.COLOR_RGB2BGR);


    Imgcodecs.imwrite(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/yolo_v3/debugAndTest.jpg", ultimate);

}
 
Example 14
Source File: ImageSaver.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
public boolean save(Mat mat) {
    Mat ultimate = new Mat();
    Imgproc.cvtColor(mat, ultimate, Imgproc.COLOR_RGB2BGR);

    Date currentTime = Calendar.getInstance().getTime();
    String strProg = "";
    if (currentTime.equals(previousTime)) {
        strProg = String.valueOf(++previousProg);
    }else{
        previousProg = 0;
    }
    String fullPath = String.format("%s/recognition_%s%s.jpg", dir.getAbsolutePath(), df.format(currentTime), strProg);
    previousTime = currentTime;
    return Imgcodecs.imwrite(fullPath, ultimate);
}
 
Example 15
Source File: OpenCVoperation.java    From Human-hair-detection with Apache License 2.0 4 votes vote down vote up
public void skinDetection2()
{
    matrix3_skindetection = new Mat(matrix2_grabcut.size(),matrix2_grabcut.type()); 
    matrix3_skindetection.setTo(new Scalar(0,0,255));
    
    Mat  src_YCrCb = new Mat(matrix2_grabcut.size(),CvType.CV_8SC3);
    Mat src_hsv = new Mat(matrix2_grabcut.size(),CvType.CV_8SC3);
    
    Imgproc.cvtColor(matrix2_grabcut, src_YCrCb, Imgproc.COLOR_BGR2YCrCb);  
    matrix2_grabcut.convertTo(src_hsv, CvType.CV_32FC3);
    Imgproc.cvtColor(src_hsv, src_hsv, Imgproc.COLOR_BGR2HSV);
    Core.normalize(src_hsv, src_hsv, 0.00, 255.00, Core.NORM_MINMAX,CvType.CV_32FC3);
    
    for(int r = 0 ; r< matrix2_grabcut.rows(); r++)
    {
        for(int c = 0 ; c< matrix2_grabcut.cols(); c++)
        {
            double[] Pixel_val_rgb = matrix2_grabcut.get(r, c);
            int B= (int)Pixel_val_rgb[0];
            int G= (int)Pixel_val_rgb[1];
            int R= (int)Pixel_val_rgb[2];
            boolean a1= R1(R,G,B);
            
            double[] Pixel_val_YCrCb = src_YCrCb.get(r, c);
            int Y =(int)Pixel_val_YCrCb[0];
            int Cr =(int)Pixel_val_YCrCb[1];
            int Cb =(int)Pixel_val_YCrCb[2];
            boolean a2= R2(Y,Cr,Cb);
            
            double[] Pixel_val_hsv =src_hsv.get(r,c);
            float H = (float)Pixel_val_hsv[0];
            float S = (float)Pixel_val_hsv[1];
            float V = (float)Pixel_val_hsv[2];
            boolean a3= R3(H,S,V);
            
            if(!(a1 && a2 && a3))
               matrix3_skindetection.put(r, c, new double[]{0,0,255});
            else
               matrix3_skindetection.put(r,c,sourceImage.get(r, c));
         }
    }
    Imgcodecs.imwrite(resultDirectory+skinDetectionOutput , matrix3_skindetection);
}
 
Example 16
Source File: Application.java    From opencv-object-detection with MIT License 4 votes vote down vote up
public static void main(String[] args)
{
    System.loadLibrary("opencv_java340");
    DeepNeuralNetworkProcessor processor = new DeepNeuralNetworkProcessor();
    List<DnnObject> detectObject = new ArrayList<>();
    VideoCapture capturre = new VideoCapture(0);
    while (true)
    {
       Mat frame = new Mat();
       capturre.read(frame);
       detectObject = processor.getObjectsInFrame(frame, false);
       for (DnnObject obj: detectObject)
       {
           Imgproc.rectangle(frame,obj.getLeftBottom(),obj.getRightTop(),new Scalar(255,0,0),1);
       }
       Imgcodecs.imwrite("DetectedObject.jpg",frame);
    }

}
 
Example 17
Source File: OpenCVNonMavenExamples.java    From Java-for-Data-Science with MIT License 4 votes vote down vote up
public void resizeImage() {
    Mat source = Imgcodecs.imread("cat.jpg");
    Mat resizeimage = new Mat();
    Imgproc.resize(source, resizeimage, new Size(250, 250));
    Imgcodecs.imwrite("resizedCat.jpg", resizeimage);
}
 
Example 18
Source File: ImageRecognition.java    From onetwo with Apache License 2.0 4 votes vote down vote up
private void writeDebugImage(String name, Mat outputImage) {
	this.checkDebugImageDir();
	String path = FileUtils.convertDir(debugImageDir) + name; 
       Imgcodecs.imwrite(path, outputImage);
}
 
Example 19
Source File: ImgprocessUtils.java    From classchecks with Apache License 2.0 4 votes vote down vote up
public static void imwrite(List<Mat> mats, String filePath) {
	FileUtils.isExist(filePath);
	for(int i = 0, len = mats.size(); i < len; i ++) {
		Imgcodecs.imwrite(FileUtils.buildFilePath(filePath, i+".jpg"), mats.get(i));
	}
}
 
Example 20
Source File: GeneralUtils.java    From super-cloudops with Apache License 2.0 2 votes vote down vote up
/**
 * 作用:保存图像
 *
 * @param src
 *            Mat矩阵图像
 * @param filePath
 *            要保存图像的路径及名字
 * @return
 */
public static boolean saveImg(Mat src, String filePath) {
	return Imgcodecs.imwrite(filePath, src);
}