Java Code Examples for org.opencv.imgproc.Imgproc#resize()

The following examples show how to use org.opencv.imgproc.Imgproc#resize() . 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: ImShow.java    From ImageEnhanceViaFusion with MIT License 6 votes vote down vote up
public void showImage(Mat img) {
	if (SizeCustom) {
		Imgproc.resize(img, img, new Size(Height, Width));
	}
	// Highgui.imencode(".jpg", img, matOfByte);
	// byte[] byteArray = matOfByte.toArray();
	BufferedImage bufImage = null;
	try {
		// InputStream in = new ByteArrayInputStream(byteArray);
		// bufImage = ImageIO.read(in);
		bufImage = toBufferedImage(img);
		image.setImage(bufImage);
		Window.pack();
		label.updateUI();
		Window.setVisible(true);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: MainActivity.java    From open-quartz with Apache License 2.0 6 votes vote down vote up
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();
    mGray = inputFrame.gray();

    switch (MainActivity.viewMode) {
        case MainActivity.VIEW_MODE_RGBA:
            return mRgba;

        case MainActivity.VIEW_MODE_HIST:
            return mRgba;

        case MainActivity.VIEW_MODE_CANNY:
            Imgproc.Canny(mGray, mIntermediateMat, 80, 100);
            Imgproc.cvtColor(mIntermediateMat, mGray, Imgproc.COLOR_GRAY2BGRA, 4);
            return mGray;

        case MainActivity.VIEW_MODE_SOBEL:
            Imgproc.Sobel(mGray, mGray, CvType.CV_8U, 1, 1);
            //			Core.convertScaleAbs(mIntermediateMat, mIntermediateMat, 10, 0);
            Imgproc.cvtColor(mGray, mGray, Imgproc.COLOR_GRAY2BGRA, 4);
            return mGray;

        case MainActivity.VIEW_MODE_PIXELIZE:
            Imgproc.resize(mGray, mIntermediateMat, mSize0, 0.1, 0.1,
                Imgproc.INTER_NEAREST);
            Imgproc.resize(mIntermediateMat, mRgba, mRgba.size(), 0.0, 0.0,
                Imgproc.INTER_NEAREST);
            return mRgba;

        case MainActivity.VIEW_MODE_GRAY:
            return mGray;

        case MainActivity.VIEW_MODE_FEATURES:
            FindFeatures(mGray.getNativeObjAddr(), mRgba.getNativeObjAddr());
            return mRgba;

        default:
            return mRgba;
    }
}
 
Example 3
Source File: ImShow.java    From OptimizedImageEnhance with MIT License 6 votes vote down vote up
public void showImage(Mat img) {
	if (SizeCustom) {
		Imgproc.resize(img, img, new Size(Height, Width));
	}
	// Highgui.imencode(".jpg", img, matOfByte);
	// byte[] byteArray = matOfByte.toArray();
	BufferedImage bufImage = null;
	try {
		// InputStream in = new ByteArrayInputStream(byteArray);
		// bufImage = ImageIO.read(in);
		bufImage = toBufferedImage(img);
		image.setImage(bufImage);
		Window.pack();
		label.updateUI();
		Window.setVisible(true);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 4
Source File: Lines.java    From DogeCV with 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 5
Source File: Test.java    From classchecks with 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 6
Source File: Tld.java    From OpenTLDAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Output: resized zero-mean patch/pattern
 * @param inImg INPUT, outPattern OUTPUT
 * @return stdev
 */
private static double resizeZeroMeanStdev(final Mat inImg, Mat outPattern, int patternSize){
	if(inImg == null || outPattern == null){
		return -1;
	}
	
	Imgproc.resize(inImg, outPattern, new Size(patternSize, patternSize));
	final MatOfDouble mean = new MatOfDouble();
	final MatOfDouble stdev = new MatOfDouble();
	Core.meanStdDev(outPattern, mean, stdev);
	outPattern.convertTo(outPattern, CvType.CV_32F);
	Core.subtract(outPattern, new Scalar(mean.toArray()[0]), outPattern);
	
	return stdev.toArray()[0];
}
 
Example 7
Source File: LocalBinaryPattern.java    From Android-Face-Recognition-with-Deep-Learning-Library with Apache License 2.0 5 votes vote down vote up
@Override
public PreProcessor preprocessImage(PreProcessor preProcessor) {
    List<Mat> images = preProcessor.getImages();
    List<Mat> processed = new ArrayList<Mat>();
    for(Mat img : images){
        // Resize for Performance enhancement
        PreferencesHelper preferencesHelper = new PreferencesHelper(preProcessor.getContext());
        Size size = new Size(preferencesHelper.getN(), preferencesHelper.getN());
        Imgproc.resize(img, img, size);
        Mat lbp = new Mat(img.rows()-2, img.cols()-2, img.type());
        for (int i=1; i<img.rows()-1; i++){
            for (int j=1; j<img.cols()-1; j++){
                BitSet out = new BitSet(8);
                double cen = img.get(i, j)[0];
                if(img.get(i-1, j-1)[0] > cen) out.set(0);
                if(img.get(i-1, j)[0] > cen) out.set(1);
                if(img.get(i-1, j+1)[0] > cen) out.set(2);
                if(img.get(i, j+1)[0] > cen) out.set(3);
                if(img.get(i+1,j+1)[0] > cen) out.set(4);
                if(img.get(i+1,j)[0] > cen) out.set(5);
                if(img.get(i+1,j-1)[0] > cen) out.set(6);
                if(img.get(i,j-1)[0] > cen) out.set(7);
                int value = 0;
                for(int k=0; k<out.length(); k++){
                    int index = out.nextSetBit(k);
                    value += Math.pow(2,out.length() - 1 - index);
                    k = index;
                }
                lbp.put(i-1, j-1, value);
            }
        }
        processed.add(lbp);
    }
    preProcessor.setImages(processed);
    return preProcessor;
}
 
Example 8
Source File: ImageTest.java    From onetwo with 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 9
Source File: Transform.java    From FTCVision with MIT License 5 votes vote down vote up
private static void resize(Mat img, Size size) {
    int interpolation;
    if (MathUtil.equal(size.area(), img.size().area()))
        return;
    else if (size.width > img.size().width && size.height > img.size().height)
        interpolation = Imgproc.CV_INTER_CUBIC; //enlarge image
    else if (size.width < img.size().width && size.height < img.size().height)
        interpolation = Imgproc.CV_INTER_AREA; //shrink image
    else
        interpolation = Imgproc.CV_INTER_LINEAR; //not entirely sure, so use safe option
    Imgproc.resize(img, img, size, 0, 0, interpolation);
}
 
Example 10
Source File: Element.java    From SikuliNG with MIT License 5 votes vote down vote up
public Mat getResizedMat(double factor) {
  Mat newMat = getContent();
  if (isValid()) {
    newMat = getNewMat();
    Size newS = new Size(w * factor, h * factor);
    Imgproc.resize(getContent(), newMat, newS, 0, 0, Imgproc.INTER_AREA);
  }
  return newMat;
}
 
Example 11
Source File: CVProcessor.java    From CVScanner with GNU General Public License v3.0 5 votes vote down vote up
public static List<MatOfPoint> findContoursForMRZ(Mat src){
    Mat img = src.clone();
    src.release();
    double ratio = getScaleRatio(img.size());
    int width = (int) (img.size().width / ratio);
    int height = (int) (img.size().height / ratio);
    Size newSize = new Size(width, height);
    Mat resizedImg = new Mat(newSize, CvType.CV_8UC4);
    Imgproc.resize(img, resizedImg, newSize);

    Mat gray = new Mat();
    Imgproc.cvtColor(resizedImg, gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.medianBlur(gray, gray, 3);
    //Imgproc.blur(gray, gray, new Size(3, 3));

    Mat morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(13, 5));
    Mat dilatedImg = new Mat();
    Imgproc.morphologyEx(gray, dilatedImg, Imgproc.MORPH_BLACKHAT, morph);
    gray.release();

    Mat gradX = new Mat();
    Imgproc.Sobel(dilatedImg, gradX, CvType.CV_32F, 1, 0);
    dilatedImg.release();
    Core.convertScaleAbs(gradX, gradX, 1, 0);
    Core.MinMaxLocResult minMax = Core.minMaxLoc(gradX);
    Core.convertScaleAbs(gradX, gradX, (255/(minMax.maxVal - minMax.minVal)),
            - ((minMax.minVal * 255) / (minMax.maxVal - minMax.minVal)));
    Imgproc.morphologyEx(gradX, gradX, Imgproc.MORPH_CLOSE, morph);

    Mat thresh = new Mat();
    Imgproc.threshold(gradX, thresh, 0, 255, Imgproc.THRESH_OTSU);
    gradX.release();
    morph.release();

    morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(21, 21));
    Imgproc.morphologyEx(thresh, thresh, Imgproc.MORPH_CLOSE, morph);
    Imgproc.erode(thresh, thresh, new Mat(), new Point(-1, -1), 4);
    morph.release();

    int col = (int) resizedImg.size().width;
    int p = (int) (resizedImg.size().width * 0.05);
    int row = (int) resizedImg.size().height;
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < p; j++){
            thresh.put(i, j, 0);
            thresh.put(i, col-j, 0);
        }
    }

    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(thresh, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    hierarchy.release();

    Log.d(TAG, "contours found: " + contours.size());

    Collections.sort(contours, new Comparator<MatOfPoint>() {
        @Override
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            return Double.valueOf(Imgproc.contourArea(o2)).compareTo(Imgproc.contourArea(o1));
        }
    });

    return contours;
}
 
Example 12
Source File: DigitRecognizer.java    From MOAAP with MIT License 5 votes vote down vote up
int FindMatch(Mat test_image)
{

    //Dilate the image
    Imgproc.dilate(test_image, test_image, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(3,3)));
    //Resize the image to match it with the sample image size
    Imgproc.resize(test_image, test_image, new Size(width, height));
    //Convert the image to grayscale
    Imgproc.cvtColor(test_image, test_image, Imgproc.COLOR_RGB2GRAY);
    //Adaptive Threshold
    Imgproc.adaptiveThreshold(test_image,test_image,255,Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV,15, 2);

    Mat test = new Mat(1, test_image.rows() * test_image.cols(), CvType.CV_32FC1);
    int count = 0;
    for(int i = 0 ; i < test_image.rows(); i++)
    {
        for(int j = 0 ; j < test_image.cols(); j++) {
            test.put(0, count, test_image.get(i, j)[0]);
            count++;
        }
    }

    Mat results = new Mat(1, 1, CvType.CV_8U);

    //K-NN Prediction
    //return (int)knn.findNearest(test, 10, results);

    //SVM Prediction
    return (int)svm.predict(test);
}
 
Example 13
Source File: ImageUtils.java    From AndroidFaceRecognizer with 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 14
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 15
Source File: ImageProcessor.java    From video-stream-classification with Apache License 2.0 4 votes vote down vote up
/**
 * Method to process images
 * 
 * @param camId camera Id
 * @param frames list of VideoEventData
 * @param outputDir directory to save image files
 * @return last processed VideoEventData 
 * @throws Exception
 */
public static VideoEventData process(String camId, Iterator<VideoEventData> frames, String outputDir, VideoEventData previousProcessedEventData) throws Exception {
	VideoEventData currentProcessedEventData = new VideoEventData();
	Mat frame = null;
	double imageWidth = 640;
	double imageHeight = 480;
	Size sz = new Size(imageWidth, imageHeight);
	int frameCount = 0;
	
	//Add frames to list
	ArrayList<VideoEventData> sortedList = new ArrayList<VideoEventData>();
	while(frames.hasNext()){
		sortedList.add(frames.next());
	}
	
	//previous processed frame 
	if (previousProcessedEventData != null) {
		logger.warn("cameraId=" + camId + " previous processed timestamp=" + previousProcessedEventData.getTimestamp());
		sortedList.add(previousProcessedEventData);
	}
	
	//sort frames by timestamp
	sortedList.sort(Comparator.comparing(VideoEventData::getTimestamp));
	logger.warn("cameraId="+camId+" total frames="+sortedList.size());
	
	//iterate and classify every 10th frame
	for (VideoEventData eventData : sortedList) {
		frame = getMat(eventData);
		Imgproc.resize(frame, frame, sz);
		frameCount++;
		if(frameCount == 10){
			MatOfByte bytemat = new MatOfByte();
			Imgcodecs.imencode(".jpg", frame, bytemat);
			byte[] bytes = bytemat.toArray();
			String match = ImageClassifier.classifyImage(bytes);
			logger.info("Best Match "+match);
			saveImageAndData(frame, eventData, match, outputDir);
			frameCount = 0;
		}
			currentProcessedEventData = eventData;
	   }
		return currentProcessedEventData;
	}
 
Example 16
Source File: FXController.java    From Face-Recognition with Apache License 2.0 4 votes vote down vote up
/**
	 * Method for face detection and tracking
	 * 
	 * @param frame
	 *            it looks for faces in this frame
	 */
	private void detectAndDisplay(Mat frame)
	{
		MatOfRect faces = new MatOfRect();
		Mat grayFrame = new Mat();
		
		// convert the frame in gray scale
		Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
		// equalize the frame histogram to improve the result
		Imgproc.equalizeHist(grayFrame, grayFrame);
		
		// compute minimum face size (20% of the frame height, in our case)
		if (this.absoluteFaceSize == 0)
		{
			int height = grayFrame.rows();
			if (Math.round(height * 0.2f) > 0)
			{
				this.absoluteFaceSize = Math.round(height * 0.2f);
			}
		}
		
		// detect faces
		this.faceCascade.detectMultiScale(grayFrame, faces, 1.1, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE,
				new Size(this.absoluteFaceSize, this.absoluteFaceSize), new Size());
				
		// each rectangle in faces is a face: draw them!
		Rect[] facesArray = faces.toArray(); 
		for (int i = 0; i < facesArray.length; i++) {
			Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0), 3);

			// Crop the detected faces
			Rect rectCrop = new Rect(facesArray[i].tl(), facesArray[i].br());
			Mat croppedImage = new Mat(frame, rectCrop);
			// Change to gray scale
			Imgproc.cvtColor(croppedImage, croppedImage, Imgproc.COLOR_BGR2GRAY);
			// Equalize histogram
			Imgproc.equalizeHist(croppedImage, croppedImage);
			// Resize the image to a default size
			Mat resizeImage = new Mat();
			Size size = new Size(250,250);
			Imgproc.resize(croppedImage, resizeImage, size);
			
			// check if 'New user' checkbox is selected
			// if yes start collecting training data (50 images is enough)
			if ((newUser.isSelected() && !newname.isEmpty())) {
				if (index<20) {
					Imgcodecs.imwrite("resources/trainingset/combined/" +
					random + "-" + newname + "_" + (index++) + ".png", resizeImage);
				}
			}
//			int prediction = faceRecognition(resizeImage);
			double[] returnedResults = faceRecognition(resizeImage);
			double prediction = returnedResults[0];
			double confidence = returnedResults[1];
			
//			System.out.println("PREDICTED LABEL IS: " + prediction);
			int label = (int) prediction;
			String name = "";
			if (names.containsKey(label)) {
				name = names.get(label);
			} else {
				name = "Unknown";
			}
			
			// Create the text we will annotate the box with:
//            String box_text = "Prediction = " + prediction + " Confidence = " + confidence;
            String box_text = "Prediction = " + name + " Confidence = " + confidence;
            // Calculate the position for annotated text (make sure we don't
            // put illegal values in there):
            double pos_x = Math.max(facesArray[i].tl().x - 10, 0);
            double pos_y = Math.max(facesArray[i].tl().y - 10, 0);
            // And now put it into the image:
            Imgproc.putText(frame, box_text, new Point(pos_x, pos_y), 
            		Core.FONT_HERSHEY_PLAIN, 1.0, new Scalar(0, 255, 0, 2.0));
		}
	}
 
Example 17
Source File: MainActivity.java    From pasm-yolov3-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Mat doInBackground(Mat... mats) {
    Mat mRgbaTemp = mats[0];
    ImageProcessor processor = new ImageProcessor(getApplicationContext(), classifier.getLabels());
    if (myBitmap != null){
        smallBitmap = Bitmap.createScaledBitmap(myBitmap, INPUT_SIZE, INPUT_SIZE, false);
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;

        float ratio = (float)myBitmap.getWidth() / (float)myBitmap.getHeight();
        Bitmap reducedBitmap = Bitmap.createScaledBitmap(myBitmap, (int) (height * ratio), height, false);

        this.publishProgress(reducedBitmap);
        processor.loadImage(myBitmap, INPUT_SIZE, INPUT_SIZE);
    }else{
        smallBitmap = Bitmap.createBitmap(INPUT_SIZE, INPUT_SIZE, Bitmap.Config.RGB_565);
        Bitmap bigBitmap = Bitmap.createBitmap(mRgbaF.width(), mRgbaF.height(), Bitmap.Config.RGB_565);
        Mat mRgbaFixedSize = new Mat(INPUT_SIZE, INPUT_SIZE, CvType.CV_8UC4);

        Core.transpose(mRgbaTemp, mRgbaT);
        Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
        Core.flip(mRgbaF, mRgbaTemp, 1 );

        Imgproc.resize(mRgbaTemp, mRgbaFixedSize, new Size(INPUT_SIZE, INPUT_SIZE), 0,0, 0);

        Utils.matToBitmap(mRgbaFixedSize, smallBitmap);
        Utils.matToBitmap(mRgbaTemp, bigBitmap);

        this.publishProgress(bigBitmap);
        processor.loadImage(bigBitmap, INPUT_SIZE, INPUT_SIZE);
        //OLD Toast.makeText(getApplicationContext(), "Nessuna immagine caricata", Toast.LENGTH_SHORT).show();
    }

    List<Classifier.Recognition> recognitions = classifier.recognizeImage(smallBitmap);
    Mat mat = processor.drawBoxes(recognitions, 0.2);
    imageSaver.save(mat); // remove for realtime processing!
    return mat;
}
 
Example 18
Source File: FaceDetector.java    From GenderRecognizer with MIT License 4 votes vote down vote up
public Mat[] snipFace(String image, Size size){
	
	Mat matImage = Highgui.imread(image, Highgui.IMREAD_UNCHANGED);
	
	Rect[] rectFace = detectFace(matImage);
	int rectFaceLength = rectFace.length;

	Mat[] matFace = new Mat[rectFaceLength];
	
	for(int i=0; i<rectFaceLength; i++){
		
		matFace[i] = matImage.submat(rectFace[i]);
		Imgproc.resize(matFace[i], matFace[i], size);
		
		//Highgui.imwrite(image.substring(0, image.length()-4)+"Snipped"+i+image.substring(image.length()-4), matFace[i]);
	}
	
	return matFace;
}
 
Example 19
Source File: MainActivity.java    From hand_finger_recognition_android with MIT License 2 votes vote down vote up
public boolean onTouch(View v, MotionEvent event) {
    int cols = mRgba.cols();
    int rows = mRgba.rows();

    int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
    int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;

    int x = (int)event.getX() - xOffset;
    int y = (int)event.getY() - yOffset;

    Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");

    if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;

    Rect touchedRect = new Rect();

    touchedRect.x = (x>5) ? x-5 : 0;
    touchedRect.y = (y>5) ? y-5 : 0;

    touchedRect.width = (x+5 < cols) ? x + 5 - touchedRect.x : cols - touchedRect.x;
    touchedRect.height = (y+5 < rows) ? y + 5 - touchedRect.y : rows - touchedRect.y;

    Mat touchedRegionRgba = mRgba.submat(touchedRect);

    Mat touchedRegionHsv = new Mat();
    Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);

    // Calculate average color of touched region
    mBlobColorHsv = Core.sumElems(touchedRegionHsv);
    int pointCount = touchedRect.width*touchedRect.height;
    for (int i = 0; i < mBlobColorHsv.val.length; i++)
        mBlobColorHsv.val[i] /= pointCount;

    mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);

    Log.i(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
            ", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");

    mDetector.setHsvColor(mBlobColorHsv);

    Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);

    mIsColorSelected = true;

    touchedRegionRgba.release();
    touchedRegionHsv.release();

    return false; // don't need subsequent touch events
}
 
Example 20
Source File: ColorBlobDetectionActivity.java    From OpenCV-AndroidSamples with MIT License 2 votes vote down vote up
public boolean onTouch(View v, MotionEvent event) {
    int cols = mRgba.cols();
    int rows = mRgba.rows();

    int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
    int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;

    int x = (int)event.getX() - xOffset;
    int y = (int)event.getY() - yOffset;

    Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");

    if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;

    Rect touchedRect = new Rect();

    touchedRect.x = (x>4) ? x-4 : 0;
    touchedRect.y = (y>4) ? y-4 : 0;

    touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
    touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;

    Mat touchedRegionRgba = mRgba.submat(touchedRect);

    Mat touchedRegionHsv = new Mat();
    Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);

    // Calculate average color of touched region
    mBlobColorHsv = Core.sumElems(touchedRegionHsv);
    int pointCount = touchedRect.width*touchedRect.height;
    for (int i = 0; i < mBlobColorHsv.val.length; i++)
        mBlobColorHsv.val[i] /= pointCount;

    mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);

    Log.i(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
            ", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");

    mDetector.setHsvColor(mBlobColorHsv);

    Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);

    mIsColorSelected = true;

    touchedRegionRgba.release();
    touchedRegionHsv.release();

    return false; // don't need subsequent touch events
}