Java Code Examples for org.opencv.imgproc.Imgproc

The following examples show how to use org.opencv.imgproc.Imgproc. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: MOAAP   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
void HOGDescriptor() {
    Mat grayMat = new Mat();
    Mat people = new Mat();

    //Converting the image to grayscale
    Imgproc.cvtColor(originalMat, grayMat, Imgproc.COLOR_BGR2GRAY);

    HOGDescriptor hog = new HOGDescriptor();
    hog.setSVMDetector(HOGDescriptor.getDefaultPeopleDetector());

    MatOfRect faces = new MatOfRect();
    MatOfDouble weights = new MatOfDouble();

    hog.detectMultiScale(grayMat, faces, weights);
    originalMat.copyTo(people);
    //Draw faces on the image
    Rect[] facesArray = faces.toArray();
    for (int i = 0; i < facesArray.length; i++)
        Imgproc.rectangle(people, facesArray[i].tl(), facesArray[i].br(), new Scalar(100), 3);

    //Converting Mat back to Bitmap
    Utils.matToBitmap(people, currentBitmap);
    imageView.setImageBitmap(currentBitmap);
}
 
Example 2
Source Project: SikuliNG   Source File: Finder.java    License: MIT License 6 votes vote down vote up
public static Mat detectEdges(Mat mSource) {
  Mat mSourceGray = Element.getNewMat();
  Mat mDetectedEdges = Element.getNewMat();

  int edgeThresh = 1;
  int lowThreshold = 100;
  int ratio = 3;
  int kernelSize = 5;
  int blurFilterSize = 3;

  if (mSource.channels() == 1) {
    mSourceGray = mSource;
  } else {
    Imgproc.cvtColor(mSource, mSourceGray, toGray);
  }
  Imgproc.blur(mSourceGray, mDetectedEdges, new Size(blurFilterSize, blurFilterSize));
  Imgproc.Canny(mDetectedEdges, mDetectedEdges,
          lowThreshold, lowThreshold * ratio, kernelSize, false);
  return mDetectedEdges;
}
 
Example 3
Source Project: FtcSamples   Source File: GripPipeline.java    License: MIT License 6 votes vote down vote up
/**
 * Softens an image using one of several filters.
 * @param input The image on which to perform the blur.
 * @param type The blurType to perform.
 * @param doubleRadius The radius for the blur.
 * @param output The image in which to store the output.
 */
private void blur(Mat input, BlurType type, double doubleRadius,
	Mat output) {
	int radius = (int)(doubleRadius + 0.5);
	int kernelSize;
	switch(type){
		case BOX:
			kernelSize = 2 * radius + 1;
			Imgproc.blur(input, output, new Size(kernelSize, kernelSize));
			break;
		case GAUSSIAN:
			kernelSize = 6 * radius + 1;
			Imgproc.GaussianBlur(input,output, new Size(kernelSize, kernelSize), radius);
			break;
		case MEDIAN:
			kernelSize = 2 * radius + 1;
			Imgproc.medianBlur(input, output, kernelSize);
			break;
		case BILATERAL:
			Imgproc.bilateralFilter(input, output, -1, radius, radius);
			break;
	}
}
 
Example 4
public Optional<MatOfPoint2f> findChessboard(Mat mat) {

		final MatOfPoint2f imageCorners = new MatOfPoint2f();

		final boolean found = Calib3d.findChessboardCorners(mat, boardSize, imageCorners,
				Calib3d.CALIB_CB_ADAPTIVE_THRESH | Calib3d.CALIB_CB_NORMALIZE_IMAGE);

		if (logger.isTraceEnabled()) logger.trace("found chessboard corners {}", found);

		if (found) {
			// optimization
			Imgproc.cornerSubPix(mat, imageCorners, new Size(1, 1), new Size(-1, -1), term);

			return Optional.of(imageCorners);
		}
		return Optional.empty();
	}
 
Example 5
Source Project: SimpleDocumentScanner-Android   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
/**
     * Apply a threshold to give the "scanned" look
     *
     * NOTE:
     * See the following link for more info http://docs.opencv.org/3.1.0/d7/d4d/tutorial_py_thresholding.html#gsc.tab=0
     * @param src A valid Mat
     * @return The processed Bitmap
     */
    private Bitmap applyThreshold(Mat src) {
        Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY);

        // Some other approaches
//        Imgproc.adaptiveThreshold(src, src, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 15);
//        Imgproc.threshold(src, src, 0, 255, Imgproc.THRESH_BINARY + Imgproc.THRESH_OTSU);

        Imgproc.GaussianBlur(src, src, new Size(5, 5), 0);
        Imgproc.adaptiveThreshold(src, src, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 11, 2);

        Bitmap bm = Bitmap.createBitmap(src.width(), src.height(), Bitmap.Config.ARGB_8888);
        org.opencv.android.Utils.matToBitmap(src, bm);

        return bm;
    }
 
Example 6
Source Project: SikuliX1   Source File: SXOpenCV.java    License: MIT License 6 votes vote down vote up
public static Mat optimize(Mat mimg, float rFactor, Image.Interpolation interpolation) {
  Imgproc.cvtColor(mimg, mimg, Imgproc.COLOR_BGR2GRAY);

  // sharpen original image to primarily get rid of sub pixel rendering artifacts
  mimg = unsharpMask(mimg, 3);

  if (rFactor > 0 && rFactor != 1) {
    resize(mimg, rFactor, interpolation);
  }

  // sharpen the enlarged image again
  mimg = unsharpMask(mimg, 5);

  // invert in case of mainly dark background
  if (Core.mean(mimg).val[0] < 127) {
    Core.bitwise_not(mimg, mimg);
  }
  return mimg;
}
 
Example 7
Source Project: OpenCV-Android-Object-Detection   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void initializeOpenCVDependencies() throws IOException {
    mOpenCvCameraView.enableView();
    detector = FeatureDetector.create(FeatureDetector.ORB);
    descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
    matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
    img1 = new Mat();
    AssetManager assetManager = getAssets();
    InputStream istr = assetManager.open("a.jpeg");
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    Utils.bitmapToMat(bitmap, img1);
    Imgproc.cvtColor(img1, img1, Imgproc.COLOR_RGB2GRAY);
    img1.convertTo(img1, 0); //converting the image to match with the type of the cameras image
    descriptors1 = new Mat();
    keypoints1 = new MatOfKeyPoint();
    detector.detect(img1, keypoints1);
    descriptor.compute(img1, keypoints1, descriptors1);

}
 
Example 8
private static ArrayList<Rect> getContourArea(Mat mat) {
	Mat hierarchy = new Mat();
	Mat image = mat.clone();
	List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
	Imgproc.findContours(image, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
	Rect rect = null;
	double maxArea = 300;
	ArrayList<Rect> arr = new ArrayList<Rect>();
	for (int i = 0; i < contours.size(); i++) {
		Mat contour = contours.get(i);
		double contourArea = Imgproc.contourArea(contour);
		if (contourArea > maxArea) {
			rect = Imgproc.boundingRect(contours.get(i));
			arr.add(rect);
		}
	}
	return arr;
}
 
Example 9
Source Project: super-cloudops   Source File: ResizeUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Mat resize(Mat src, Size dsize) {
	try {
		Mat temp = trimImg(src);
		src = temp;
	} catch (Exception e) {
		System.out.println(e);
	}

	src = clearWhite(src);

	Mat dst = new Mat();
	// 区域插值(INTER_AREA):图像放大时类似于线性插值,图像缩小时可以避免波纹出现。
	Imgproc.resize(src, dst, dsize, 0, 0, Imgproc.INTER_AREA);

	// 腐蚀
	dst = GeneralUtils.erode(dst);
	return dst;
}
 
Example 10
Source Project: super-cloudops   Source File: VideoFaceTests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * OpenCV-4.0.0 人脸识别
 * 
 * @date: 2019年5月7日12:16:55
 * @param image
 *            待处理Mat图片(视频中的某一帧)
 * @return 处理后的图片
 * @throws IOException
 */
public static Mat getFace(Mat image) throws IOException {
	// 1 读取OpenCV自带的人脸识别特征XML文件
	File faceFile = new ClassPathResourcePatternResolver().getResource("opencv/data/haarcascade_frontalface_alt.xml")
			.getFile();
	CascadeClassifier facebook = new CascadeClassifier(faceFile.getAbsolutePath());
	// 2 特征匹配类
	MatOfRect face = new MatOfRect();
	// 3 特征匹配
	facebook.detectMultiScale(image, face);
	Rect[] rects = face.toArray();
	System.out.println("匹配到 " + rects.length + " 个人脸");
	// 4 为每张识别到的人脸画一个圈
	for (int i = 0; i < rects.length; i++) {
		Imgproc.rectangle(image, new Point(rects[i].x, rects[i].y),
				new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 255, 0));
		Imgproc.putText(image, "Human", new Point(rects[i].x, rects[i].y), Imgproc.FONT_HERSHEY_SCRIPT_SIMPLEX, 1.0,
				new Scalar(0, 255, 0), 1, Imgproc.LINE_AA, false);
		// Mat dst=image.clone();
		// Imgproc.resize(image, image, new Size(300,300));
	}
	return image;
}
 
Example 11
Source Project: tutorials   Source File: FaceDetection.java    License: MIT License 6 votes vote down vote up
public static void detectFace(String sourceImagePath, String targetImagePath) {
    Mat loadedImage = loadImage(sourceImagePath);
    MatOfRect facesDetected = new MatOfRect();
    CascadeClassifier cascadeClassifier = new CascadeClassifier();
    int minFaceSize = Math.round(loadedImage.rows() * 0.1f);
    cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
    cascadeClassifier.detectMultiScale(loadedImage,
            facesDetected,
            1.1,
            3,
            Objdetect.CASCADE_SCALE_IMAGE,
            new Size(minFaceSize, minFaceSize),
            new Size()
    );
    Rect[] facesArray =  facesDetected.toArray();
    for(Rect face : facesArray) {
        Imgproc.rectangle(loadedImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
    }
    saveImage(loadedImage, targetImagePath);
}
 
Example 12
public PreProcessor preprocessImage(PreProcessor preProcessor) {
    List<Mat> images = preProcessor.getImages();
    List<Mat> processed = new ArrayList<Mat>();
    for (Mat img : images){
        preProcessor.normalize0255(img);

        /***************************************************************************************
         *    Title: Automatic calculation of low and high thresholds for the Canny operation in opencv
         *    Author: VP
         *    Date: 16.04.2013
         *    Code version: -
         *    Availability: http://stackoverflow.com
         *
         ***************************************************************************************/

        double otsu_thresh_val = Imgproc.threshold(img, img, 0, 255, Imgproc.THRESH_OTSU);
        Imgproc.Canny(img, img, otsu_thresh_val * 0.5, otsu_thresh_val);
        processed.add(img);
    }
    preProcessor.setImages(processed);
    return preProcessor;
}
 
Example 13
Source Project: OptimizedImageEnhance   Source File: RemoveBackScatter.java    License: MIT License 6 votes vote down vote up
private static Mat calWeight(Mat img) {
	Mat L = new Mat();
	img.convertTo(img, CvType.CV_8UC1);
	Imgproc.cvtColor(img, L, Imgproc.COLOR_BGR2GRAY);
	L.convertTo(L, CvType.CV_32F);
	Core.divide(L, new Scalar(255.0), L);
	// calculate Luminance weight
	Mat WC = FeatureWeight.LuminanceWeight(img, L);
	WC.convertTo(WC, L.type());
	// calculate the Saliency weight
	Mat WS = FeatureWeight.Saliency(img);
	WS.convertTo(WS, L.type());
	// calculate the Exposedness weight
	Mat WE = FeatureWeight.Exposedness(L);
	WE.convertTo(WE, L.type());
	// sum
	Mat weight = WC.clone();
	Core.add(weight, WS, weight);
	Core.add(weight, WE, weight);
	return weight;
}
 
Example 14
Source Project: Java-for-Data-Science   Source File: DetectFaceDemo.java    License: MIT License 6 votes vote down vote up
public void run() {
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  String base = "C:/Books in Progress/Java for Data Science/Chapter 10/OpenCVExamples/src/resources";
  CascadeClassifier faceDetector = 
          new CascadeClassifier(base + "/lbpcascade_frontalface.xml");
  
  Mat image = Imgcodecs.imread(base + "/images.jpg");

  MatOfRect faceVectors = new MatOfRect();
  faceDetector.detectMultiScale(image, faceVectors);

  out.println(faceVectors.toArray().length + " faces found");

  for (Rect rect : faceVectors.toArray()) {
      Imgproc.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("faceDetection.png", image);
}
 
Example 15
Source Project: DogeCV   Source File: MathFTC.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Crops an image to two specified corners
 * @param image The image to be cropped
 * @param topLeftCorner The top-left corner of the desired final image, in pixel coordinates
 * @param bottomRightCorner The bottom-right corner of the desired final image, in pixel coordinates
 * @return The cropped image
 */
public static Mat crop(Mat image, Point topLeftCorner, Point bottomRightCorner) {
    if (topLeftCorner != null) {
        if(topLeftCorner.y > 0 && topLeftCorner.y < image.height()-1 && topLeftCorner.x > 0 && topLeftCorner.x < image.width()) {
            Imgproc.rectangle(image, new Point(0,0), new Point(image.width(),topLeftCorner.y), new Scalar(0), -1);
            Imgproc.rectangle(image, new Point(0,0), new Point(topLeftCorner.x, image.height()), new Scalar(0), -1);
        }
    }
    if(bottomRightCorner != null) {
        if(bottomRightCorner.y > 0 && bottomRightCorner.y < image.height()-1 && bottomRightCorner.x > 0 && bottomRightCorner.x < image.width()) {
            Imgproc.rectangle(image, new Point(image.width(),image.height()), new Point(bottomRightCorner.x,0), new Scalar(0), -1);
            Imgproc.rectangle(image, new Point(image.width(),image.height()), new Point(0, bottomRightCorner.y), new Scalar(0), -1);
        }
    }
    return image;
}
 
Example 16
Source Project: onetwo   Source File: ImageTest.java    License: Apache License 2.0 5 votes vote down vote up
public static MatOfRect getFace(Mat src) {
	Mat result = src.clone();
	if (src.cols() > 1000 || src.rows() > 1000) {
		Imgproc.resize(src, result, new Size(src.cols() / 3, src.rows() / 3));
	}

	CascadeClassifier faceDetector = new CascadeClassifier("D:\\mydev\\java\\opencv\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_alt2.xml");
	MatOfRect objDetections = new MatOfRect();
	faceDetector.detectMultiScale(result, objDetections);
	
	return objDetections;
}
 
Example 17
Source Project: AndroidFaceRecognizer   Source File: ImageUtils.java    License: MIT License 5 votes vote down vote up
public static Mat cropFace(Mat image, Point left_eye, Point right_eye,
		double offsetPercentage, int destWidth, int destHeight){
	
	int offset_horizontal = (int)Math.floor(offsetPercentage*(double)destWidth); 
	int offset_vertical = (int)Math.floor(offsetPercentage*(double)destHeight);
	
	double distance = getDistance(left_eye, right_eye);

	double rotation = getRotationToAlign(left_eye, right_eye);
	double reference = destWidth - 2*offset_horizontal;
	double scaleFactor = distance / reference;
	
	
   	Mat rot_mat = Imgproc.getRotationMatrix2D(left_eye, rotation, 1.0);
   	Mat dst = new Mat(image.rows(), image.cols(), image.type());
   	Imgproc.warpAffine(image, dst, rot_mat, new Size(destWidth, destHeight), Imgproc.INTER_CUBIC);
   	
   	Size size = new Size(destWidth*scaleFactor, destHeight*scaleFactor);
   	Point ctr = new Point(left_eye.x - scaleFactor*offset_horizontal+size.width/2,
   			left_eye.y - scaleFactor*offset_vertical+size.height/2);
   	
   	Mat cropped = new Mat();
   	Imgproc.getRectSubPix(dst, size, ctr, cropped);
   	Mat returnMatrix = new Mat();
   	Imgproc.resize(cropped, returnMatrix, new Size(destWidth, destHeight));
	
   	return returnMatrix;
}
 
Example 18
Source Project: LPR   Source File: JavaCamera2View.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mat rgba() {
    if (mPreviewFormat == ImageFormat.NV21)
        Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
    else if (mPreviewFormat == ImageFormat.YV12)
        Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4); // COLOR_YUV2RGBA_YV12 produces inverted colors
    else if (mPreviewFormat == ImageFormat.YUV_420_888) {
        assert (mUVFrameData != null);
        Imgproc.cvtColorTwoPlane(mYuvFrameData, mUVFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21);
    } else
        throw new IllegalArgumentException("Preview Format can be NV21 or YV12");

    return mRgba;
}
 
Example 19
Source Project: FaceT   Source File: CaptureActivity.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private Scalar converScalarHsv2Rgba(Scalar hsvColor) {
    Mat pointMatRgba = new Mat();
    Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
    Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);

    return new Scalar(pointMatRgba.get(0, 0));
}
 
Example 20
Source Project: LicensePlateDiscern   Source File: JavaCameraView.java    License: MIT License 5 votes vote down vote up
@Override
public Mat rgba() {
    if (mPreviewFormat == ImageFormat.NV21)
        Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
    else if (mPreviewFormat == ImageFormat.YV12)
        Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4);  // COLOR_YUV2RGBA_YV12 produces inverted colors
    else
        throw new IllegalArgumentException("Preview Format can be NV21 or YV12");

    return mRgba;
}
 
Example 21
public PreProcessor preprocessImage(PreProcessor preProcessor) {
    List<Mat> images = preProcessor.getImages();
    List<Mat> processed = new ArrayList<Mat>();
    for (Mat img : images){
        if(img.channels()>1) {
            Imgproc.cvtColor(img, img, Imgproc.COLOR_RGBA2GRAY);
        }
        processed.add(img);
    }
    preProcessor.setImages(processed);
    return preProcessor;
}
 
Example 22
Source Project: ImageEnhanceViaFusion   Source File: WeightCalculate.java    License: MIT License 5 votes vote down vote up
public static Mat LaplacianContrast(Mat img) {
	Mat laplacian = new Mat();
	Imgproc.Laplacian(img, laplacian, img.depth());
	//Imgproc.Laplacian(img, laplacian, img.depth(), 3, 1, 0);
	Core.convertScaleAbs(laplacian, laplacian);
	return laplacian;
}
 
Example 23
Source Project: AndroidDocumentScanner   Source File: NativeClass.java    License: MIT License 5 votes vote down vote up
private boolean isRectangle(MatOfPoint2f polygon, int srcArea) {
    MatOfPoint polygonInt = MathUtils.toMatOfPointInt(polygon);

    if (polygon.rows() != 4) {
        return false;
    }

    double area = Math.abs(Imgproc.contourArea(polygon));
    if (area < srcArea * AREA_LOWER_THRESHOLD || area > srcArea * AREA_UPPER_THRESHOLD) {
        return false;
    }

    if (!Imgproc.isContourConvex(polygonInt)) {
        return false;
    }

    // Check if the all angles are more than 72.54 degrees (cos 0.3).
    double maxCosine = 0;
    Point[] approxPoints = polygon.toArray();

    for (int i = 2; i < 5; i++) {
        double cosine = Math.abs(MathUtils.angle(approxPoints[i % 4], approxPoints[i - 2], approxPoints[i - 1]));
        maxCosine = Math.max(cosine, maxCosine);
    }

    return !(maxCosine >= 0.3);
}
 
Example 24
Source Project: Camdroid   Source File: UnsharpenMaskProcessor.java    License: Apache License 2.0 5 votes vote down vote up
protected void execute() {
    out = this.rgb();

    Imgproc.blur(out, this.mask, new Size(sigma_x, sigma_x));
    Core.addWeighted(out, (double) alpha / 10, this.mask,
            ((double) beta - 10) / 10, 0, out);
}
 
Example 25
Source Project: DogeCV   Source File: CbColorFilter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void process(Mat input, Mat mask) {
    Imgproc.cvtColor(input, input, Imgproc.COLOR_RGB2YCrCb);

    // Blur it
    Imgproc.GaussianBlur(input,input,new Size(5,5),0);
    // Run in range check
    Core.inRange(input, lower, upper, mask);
    input.release();
}
 
Example 26
Source Project: FTCVision   Source File: Color.java    License: MIT License 5 votes vote down vote up
/**
 * Convert this color to a different colorspace and return a scalar
 *
 * @param to Colorspace to convert to
 * @return Scalar in other colorspace
 */
public Scalar convertColorScalar(ColorSpace to) {
    if (getColorSpace() == to)
        return getScalar();
    if (!getColorSpace().canConvertTo(to))
        throw new IllegalArgumentException("Cannot convert color to the desired color space.");

    Scalar output = this.getScalar();

    try {
        for (int i = 0; i < getColorSpace().getConversionsTo(to).length; i += 3) {
            int conversion = getColorSpace().getConversionsTo(to)[i];
            int inputDim = getColorSpace().getConversionsTo(to)[i + 1];
            int outputDim = getColorSpace().getConversionsTo(to)[i + 2];

            Mat pointMatTo = new Mat();
            Mat pointMatFrom = new Mat(1, 1, CvType.CV_8UC(inputDim), output);
            Imgproc.cvtColor(pointMatFrom, pointMatTo, conversion, outputDim);
            output = new Scalar(pointMatTo.get(0, 0));
            pointMatTo.release();
            pointMatFrom.release();
        }
    } catch (Exception ignored) {
        throw new IllegalArgumentException("Cannot convert color to the desired color space.");
    }

    return output;
}
 
Example 27
Source Project: onetwo   Source File: ImageMatchers.java    License: Apache License 2.0 5 votes vote down vote up
static public Core.MinMaxLocResult matchResult(Mat source, Mat destImage) {
       //创建于原图相同的大小,储存匹配度
       Mat result = Mat.zeros(source.rows() - destImage.rows() + 1, source.cols() - destImage.cols() + 1, CvType.CV_32FC1);
       //调用模板匹配方法
       Imgproc.matchTemplate(source, destImage, result, Imgproc.TM_SQDIFF_NORMED);
       //规格化
       Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1);
       //获得最可能点,MinMaxLocResult是其数据格式,包括了最大、最小点的位置x、y
       Core.MinMaxLocResult mlr = Core.minMaxLoc(result);
       return mlr;
}
 
Example 28
Source Project: DogeCV   Source File: Lines.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Modern OpenCV line segment detection - far better than Canny, but must be carefully adjusted.
 * @param original The original image to be scanned, as an RGB image
 * @param scale The factor by which the image is to be downscaled
 * @param minLength The minimum line segment length to be returned
 * @return A List of Lines found
 */
public static List<Line> getOpenCvLines(Mat original, int scale, double minLength) {
    Mat raw = new Mat();
    Imgproc.resize(original.clone(), raw, new Size((int) (original.size().width/scale), (int) (original.size().height/scale)));
    if(raw.channels() > 1) {
        Imgproc.cvtColor(raw, raw, Imgproc.COLOR_RGB2GRAY);
    }
    Imgproc.equalizeHist(raw, raw);
    Imgproc.blur(raw, raw, new Size(3,3));
    //Line Segment Detection 2
    Mat linesM1 = new Mat();

    detector.detect(raw, linesM1);
    ArrayList<Line> lines = new ArrayList<Line>();
    for (int x = 0; x < linesM1.rows(); x++)  {
        double[] vec = linesM1.get(x, 0);
        Point start = new Point(vec[0],vec[1]);
        Point end = new Point(vec[2], vec[3]);
        Line line = new Line(start, end);
        line = new Line(new Point((int)line.x1*scale, (int) line.y1*scale), new Point((int)line.x2*scale, (int)line.y2*scale));
        if(line.length() > minLength) lines.add(line);
    }

    raw.release();
    linesM1.release();

    return lines;
}
 
Example 29
Source Project: classchecks   Source File: Test.java    License: Apache License 2.0 5 votes vote down vote up
public static void recognitionByLBPH() {
	String modelFilePath = "E:\\classchecks\\2017417\\train\\trainLBPHModel-201704171530.xml";
	LBPHFaceRecognizer model = TrainFaces.loadLBPHModel(modelFilePath);
	Mat waitRecoMat = Imgcodecs.imread("E:\\classchecks\\2017417\\split\\14.jpg");
	//Imgcodecs.imr
	Mat preProc = PreProcessFace.rawProcessedFace(waitRecoMat);
	ImageGui.imshow(preProc, "preProc");
	Imgproc.resize(preProc, preProc, new Size(92, 112));
	//Mat reconstructMat = Recognition.reconstructFace(model, preProc);
	
	//double similarity = Recognition.getSimilarity(preProc, reconstructMat);
       //System.out.println("similarity=" + similarity);
       int pridictLabel = model.predict_label(preProc);
       System.out.println("pridictLabel=" + pridictLabel);
}
 
Example 30
Source Project: SikuliX1   Source File: Finder.java    License: MIT License 5 votes vote down vote up
private Mat doFindMatch(Mat what, Mat where, FindInput2 findInput) {
  Mat mResult = SXOpenCV.newMat();
  if (what.empty()) {
    log.error("doFindMatch: image conversion to cvMat did not work");
  } else {
    Mat mWhere = where;
    if (findInput.isGray()) {
      Imgproc.cvtColor(where, mWhere, Imgproc.COLOR_BGR2GRAY);
    }
    if (!findInput.isPlainColor()) {
      if (findInput.hasMask()) {
        Mat mask = findInput.getMask();
        Imgproc.matchTemplate(mWhere, what, mResult, Imgproc.TM_CCORR_NORMED, mask);
      } else {
        Imgproc.matchTemplate(mWhere, what, mResult, Imgproc.TM_CCOEFF_NORMED);
      }
    } else {
      Mat wherePlain = mWhere;
      Mat whatPlain = what;
      if (findInput.isBlack()) {
        Core.bitwise_not(mWhere, wherePlain);
        Core.bitwise_not(what, whatPlain);
      }
      if (findInput.hasMask()) {
        Imgproc.matchTemplate(wherePlain, what, mResult, Imgproc.TM_SQDIFF_NORMED, findInput.getMask());
      } else {
        Imgproc.matchTemplate(wherePlain, whatPlain, mResult, Imgproc.TM_SQDIFF_NORMED);
      }
      Core.subtract(Mat.ones(mResult.size(), CvType.CV_32F), mResult, mResult);
    }
  }
  return mResult;
}