Java Code Examples for org.opencv.highgui.Highgui#imwrite()
The following examples show how to use
org.opencv.highgui.Highgui#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: HighGuiUtil.java From javautils with Apache License 2.0 | 6 votes |
/** * 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 = Highgui.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)); } Highgui.imwrite(destName, image); }
Example 2
Source File: AutoCalibrationManager.java From ShootOFF with GNU General Public License v3.0 | 6 votes |
public Mat preProcessFrame(final Mat mat) { if (mat.channels() == 1) return mat.clone(); final Mat newMat = new Mat(mat.rows(), mat.cols(), CvType.CV_8UC1); Imgproc.cvtColor(mat, newMat, Imgproc.COLOR_BGR2GRAY); if (logger.isTraceEnabled()) { String filename = String.format("grayscale.png"); final File file = new File(filename); filename = file.toString(); Highgui.imwrite(filename, newMat); } return newMat; }
Example 3
Source File: AutoCalibrationManager.java From ShootOFF with GNU General Public License v3.0 | 6 votes |
private void blankRotatedRect(Mat mat, final RotatedRect rect) { final Mat tempMat = Mat.zeros(mat.size(), CvType.CV_8UC1); final Point points[] = new Point[4]; rect.points(points); for (int i = 0; i < 4; ++i) { Core.line(tempMat, points[i], points[(i + 1) % 4], new Scalar(255, 255, 255)); } final Mat tempMask = Mat.zeros((mat.rows() + 2), (mat.cols() + 2), CvType.CV_8UC1); Imgproc.floodFill(tempMat, tempMask, rect.center, new Scalar(255, 255, 255), null, new Scalar(0, 0, 0), new Scalar(254, 254, 254), 4); if (logger.isTraceEnabled()) { String filename = String.format("poly.png"); final File file = new File(filename); filename = file.toString(); Highgui.imwrite(filename, tempMat); } mat.setTo(new Scalar(0, 0, 0), tempMat); }
Example 4
Source File: FaceDetector.java From GenderRecognizer with MIT License | 6 votes |
public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); String imagePath = "C:\\Users\\admin\\Desktop\\a.png"; FaceDetector faceDetector = new FaceDetector(); Mat[] mats = faceDetector.snipFace(imagePath, new Size(90, 90)); int i=0; for(Mat mat: mats){ Highgui.imwrite(imagePath.substring(0, imagePath.length()-4)+"Snipped"+i+imagePath.substring(imagePath.length()-4), mat); i++; } System.out.println("Done!!!"); }
Example 5
Source File: HighGuiUtil.java From javautils with Apache License 2.0 | 5 votes |
/** * 二值化 * * @param oriImg * @param outputImg */ public static void binarization(String oriImg, String outputImg) { Mat img = Highgui.imread(oriImg); Imgproc.cvtColor(img, img, Imgproc.COLOR_RGB2GRAY); // Imgproc.adaptiveThreshold(img, img, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 25, 10); Highgui.imwrite(outputImg, img); }
Example 6
Source File: HighGuiUtil.java From javautils with Apache License 2.0 | 5 votes |
/** * 边缘检测的原理:检测出图像中所有灰度值变化较大的点,而且这些点连起来构成若干线条,这些线条就称之为图像的边缘。 * @param oriImg * @param dstImg * @param threshold */ public static void canny(String oriImg, String dstImg, int threshold) { Mat img = Highgui.imread(oriImg); Imgproc.cvtColor(img, img, Imgproc.COLOR_BGR2GRAY); /**Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, boolean L2gradient) * 第一个参数,InputArray类型的image,输入图像,即源图像,填Mat类的对象即可,且需为单通道8位图像。 * 第二个参数,OutputArray类型的edges,输出的边缘图,需要和源图片有一样的尺寸和类型。 * 第三个参数,double类型的threshold1,第一个滞后性阈值。 * 第四个参数,double类型的threshold2,第二个滞后性阈值。 * 第五个参数,int类型的apertureSize,表示应用Sobel算子的孔径大小,其有默认值3。 * 第六个参数,bool类型的L2gradient,一个计算图像梯度幅值的标识,有默认值false。 */ Imgproc.Canny(img, img, threshold, threshold * 3, 3, true); Highgui.imwrite(dstImg, img); }
Example 7
Source File: JavaShotDetector.java From ShootOFF with GNU General Public License v3.0 | 5 votes |
private void addShot(Frame workingFrame, PixelCluster pc) { final Optional<ShotColor> color = pc.getColor(workingFrame.getOriginalMat(), colorDistanceFromRed); if (!color.isPresent()) { if (logger.isDebugEnabled()) logger.debug("Processing Shot: Shot Rejected By Lack Of Color Density"); return; } final double x = pc.centerPixelX; final double y = pc.centerPixelY; if (super.addShot(color.get(), x, y, workingFrame.getTimestamp(), true) && Configuration.getConfig().isDebugShotsRecordToFiles()) { final Mat debugFrame = new Mat(); Imgproc.cvtColor(workingFrame.getOriginalMat(), debugFrame, Imgproc.COLOR_HSV2BGR); String filename = String.format("shot-%d-%d-%d_orig.png", cameraManager.cameraTimeToShotTime(workingFrame.getTimestamp()), (int) pc.centerPixelX, (int) pc.centerPixelY); final File file = new File(filename); filename = file.toString(); Highgui.imwrite(filename, debugFrame); for (final Pixel p : pc) { if (javafx.scene.paint.Color.GREEN.equals(color.get())) { final double[] greenColor = { 0, 255, 0 }; debugFrame.put(p.y, p.x, greenColor); } else { final double[] redColor = { 0, 0, 255 }; debugFrame.put(p.y, p.x, redColor); } } final File outputfile = new File( String.format("shot-%d-%d-%d.png", cameraManager.cameraTimeToShotTime(workingFrame.getTimestamp()), (int) pc.centerPixelX, (int) pc.centerPixelY)); filename = outputfile.toString(); Highgui.imwrite(filename, debugFrame); } }
Example 8
Source File: AutoCalibrationManager.java From ShootOFF with GNU General Public License v3.0 | 5 votes |
private List<MatOfPoint2f> findPatterns(Mat mat, boolean findMultiple) { final List<MatOfPoint2f> patternList = new ArrayList<>(); int count = 0; while (true) { final Optional<MatOfPoint2f> boardCorners = findChessboard(mat); if (boardCorners.isPresent()) { patternList.add(boardCorners.get()); if (!findMultiple) break; final RotatedRect rect = getPatternDimensions(boardCorners.get()); blankRotatedRect(mat, rect); if (logger.isTraceEnabled()) { String filename = String.format("blanked-box-%d.png", count); final File file = new File(filename); filename = file.toString(); Highgui.imwrite(filename, mat); } // Shortcut to not try to find three+ patterns // We never should see more than two but maybe that'll change // in the future findMultiple = false; } else { break; } count++; } return patternList; }
Example 9
Source File: VideoReaderTest.java From HadoopCV with Apache License 2.0 | 5 votes |
public static void main(String[] args) { System.out.println(System.getProperty("java.class.path")); System.out.println(System.getProperty("java.library.path")); System.loadLibrary(Core.NATIVE_LIBRARY_NAME); VideoCapture camera = new VideoCapture("data/bike.avi"); MatOfByte frame = new MatOfByte(); int i = 0; while(true){ if (camera.read(frame)){ System.out.println("Frame Obtained"); System.out.println("Captured Frame Width " + frame.width() + " Height " + frame.height()); System.out.println(frame.dump()); Highgui.imwrite("tmp\\image\\camera"+(i++)+".jpg", frame); //Highgui.imencode(ext, img, buf) }else{ break; } } camera.release(); }
Example 10
Source File: Predict.java From GenderRecognizer with MIT License | 5 votes |
public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); WeightedStandardPixelTrainer weightedStandardPixelTrainer = new WeightedStandardPixelTrainer(); //sample file String imageFilePath = "src/res/sample/sample.jpg"; Mat[] faces = new FaceDetector().snipFace(imageFilePath, new Size(90, 90)); //experience file weightedStandardPixelTrainer.load("src/res/knowledge/Knowledge.log"); int faceNo=1; for(Mat face: faces){ int prediction = weightedStandardPixelTrainer.predict(face); if(prediction==-1){ System.out.println("I think " + faceNo + " is not a face."); Highgui.imwrite("src/res/sample/" + faceNo + "_noface.jpg", face); }else if(prediction==0){ System.out.println("I think " + faceNo + " is a female."); Highgui.imwrite("src/res/sample/" + faceNo + "_female.jpg", face); }else{ System.out.println("I think " + faceNo + " is a male."); Highgui.imwrite("src/res/sample/" + faceNo + "_male.jpg", face); } faceNo++; } System.out.println("Operation Successful!!!"); }
Example 11
Source File: Proc.java From android-object-distance with Apache License 2.0 | 4 votes |
public static double findMarkerWidth(String imgPath){ Mat frame = Highgui.imread(imgPath); Mat gscale = new Mat(); Mat blur = new Mat(); Mat edged = new Mat(); // convert the image to grayscale, blur it, and detect edges if(frame.channels()>1) Imgproc.cvtColor(frame, gscale, Imgproc.COLOR_BGR2GRAY); else gscale = frame; Imgproc.GaussianBlur(gscale, blur, new Size(5, 5), 0); Imgproc.Canny(blur, edged, 35, 125); // find the contours in the edged image and keep the largest one; // we'll assume that this is our piece of paper in the image List<MatOfPoint> contours = new ArrayList<>(); Mat hierarchy = new Mat(edged.width(), edged.height(), CvType.CV_8UC1); Imgproc.findContours(edged.clone(), contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); int max_idx = 0; // if any contour exist... if (hierarchy.size().height > 0 && hierarchy.size().width > 0) { double max_area = 0; double area; // find the contour with largest area for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0]) { area = Imgproc.contourArea(contours.get(idx)); if(area > max_area){ max_area = area; max_idx = idx; } Imgproc.drawContours(frame, contours, idx, new Scalar(0, 0, 255)); } //Riz: Save File //Imgproc.drawContours(frame, contours, max_idx, new Scalar(250, 0, 0)); byte[] bytes = new byte[ frame.rows() * frame.cols() * frame.channels() ]; File file = new File(CameraActivity.activity.getExternalFilesDir(null), "pic_contour"+ Integer.toString(pic_count) + ".jpg"); pic_count++; Boolean bool = null; String filename = file.toString(); bool = Highgui.imwrite(filename, frame); if (bool == true) Log.d(LOG_TAG, "SUCCESS writing image to external storage"); else Log.d(LOG_TAG, "Fail writing image to external storage"); Log.i(LOG_TAG, "Max Area: " + Double.toString(max_area)); } else{ Log.e(LOG_TAG, "No Contour Found!"); } MatOfPoint2f newPoint = new MatOfPoint2f(contours.get(max_idx).toArray()); return Imgproc.arcLength(newPoint, true); }
Example 12
Source File: AutoCalibrationManager.java From ShootOFF with GNU General Public License v3.0 | 4 votes |
@Override public void process(Frame frame) { if (!patternSet) { calibrationListener.setArenaBackground("white.png"); patternSet = true; lastSample = System.currentTimeMillis(); return; } if (completed || (System.currentTimeMillis() - lastSample) < SAMPLE_DELAY) return; final Scalar mean = Core.mean(frame.getOriginalMat()); if (origMean == 0) origMean = mean.val[0]; logger.trace("{} {}", mean.val[0], TARGET_THRESH); if (mean.val[0] > TARGET_THRESH) { if (!camera.decreaseExposure()) completed = true; } else { completed = true; } if (logger.isTraceEnabled()) { String filename = String.format("exposure-%d.png", lastSample); final File file = new File(filename); filename = file.toString(); Highgui.imwrite(filename, frame.getOriginalMat()); } tries++; if (tries == NUM_TRIES) completed = true; if (completed) { if (mean.val[0] > origMean * .95 || mean.val[0] < .6 * TARGET_THRESH) { camera.resetExposure(); logger.info("Failed to adjust exposure, mean originally {} lowest {}", origMean, mean.val[0]); } else { logger.info("Exposure lowered to {} mean from {}", mean.val[0], origMean); } } lastSample = System.currentTimeMillis(); }