Java Code Examples for org.opencv.core.Mat#width()

The following examples show how to use org.opencv.core.Mat#width() . 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: DetectObject.java    From classchecks with Apache License 2.0 7 votes vote down vote up
/**
 * 
* @Title: detectMany 
* @Description: 检测多人图片,返回检测的人脸区域对象
* @param mImgSRC
* @return
* MatOfRect
 */
public static MatOfRect detectMany(Mat mImgSRC) {
	
	if(mImgSRC.empty()) {
		LOG.info("检测多人图片检测时没有找到图片");
		return null;
	}
	// 人脸检测器文件的所在路径的文件夹名称数组
	String [] pathKey = {ServletContextHolder.getOpenCVHaarcascades(), "haarcascade_frontalface_alt.xml"};
	CascadeClassifier cascade = new CascadeClassifier(FileUtils.buildFilePath(pathKey));
	if(cascade.empty()) {
		LOG.info("人脸检测级联加载器为null");
		return null;
	}
	// 记录搜索到的人脸区域
	MatOfRect mOfRect = new MatOfRect();
	// 用于计算缩放比例
	int scaledWidth = mImgSRC.width();
	detectManyObject(mImgSRC, cascade, mOfRect, scaledWidth);
	if(mOfRect.toArray().length <= 0) {
		LOG.info("没有检测到人脸...");
		return null;
	}
	return mOfRect;
}
 
Example 2
Source File: NativeClass.java    From AndroidDocumentScanner with MIT License 6 votes vote down vote up
public MatOfPoint2f getPoint(Bitmap bitmap) {

        Mat src = ImageUtils.bitmapToMat(bitmap);

        // Downscale image for better performance.
        double ratio = DOWNSCALE_IMAGE_SIZE / Math.max(src.width(), src.height());
        Size downscaledSize = new Size(src.width() * ratio, src.height() * ratio);
        Mat downscaled = new Mat(downscaledSize, src.type());
        Imgproc.resize(src, downscaled, downscaledSize);

        List<MatOfPoint2f> rectangles = getPoints(downscaled);
        if (rectangles.size() == 0) {
            return null;
        }
        Collections.sort(rectangles, AreaDescendingComparator);
        MatOfPoint2f largestRectangle = rectangles.get(0);
        MatOfPoint2f result = MathUtils.scaleRectangle(largestRectangle, 1f / ratio);
        return result;
    }
 
Example 3
Source File: TextRecognizer.java    From SikuliX1 with MIT License 6 votes vote down vote up
protected <SFIRBS> String doRead(SFIRBS from) {
  try {
    String text = "";
    if (from instanceof Mat) {
      Mat img = ((Mat) from).clone();
      if (!img.empty()) {
        img = SXOpenCV.optimize(img, options.factor(), options.resizeInterpolation());
        byte[] bytes = new byte[img.width() * img.height()];
        int n = img.get(0, 0, bytes);
        text = getTesseractAPI().doOCR(img.width(), img.height(), ByteBuffer.wrap(bytes), null, 8);
      } else {
        return "";
      }
    } else {
      BufferedImage bimg = SXOpenCV.optimize(Element.getBufferedImage(from), options.factor(), options.resizeInterpolation());
      text = getTesseractAPI().doOCR(bimg);
    }
    return text.trim().replace("\n\n", "\n");
  } catch (TesseractException e) {
    Debug.error("OCR: read: Tess4J: doOCR: %s", e.getMessage());
    return "";
  }
}
 
Example 4
Source File: RotationUtils.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 垂直旋转90度
 * 
 * @param mat
 * @return
 */
public static Mat rotation(Mat mat) {
	int len, wid;
	if (mat.width() > mat.height()) {
		len = mat.width();
		wid = mat.height();
	} else {
		len = mat.height();
		wid = mat.width();
	}

	// 得到旋转矩阵算子
	Mat matrix = Imgproc.getRotationMatrix2D(new Point(len / 2, len / 2), 90, 1);

	Mat CorrectImg = new Mat(new Size(len, len), mat.type());

	Imgproc.warpAffine(mat, CorrectImg, matrix, CorrectImg.size(), Imgproc.INTER_LINEAR, 0, new Scalar(0, 0, 0));

	int extend = 18;

	Mat temp = new Mat(CorrectImg, new Rect(0, len - wid + extend, len, wid - 2 * extend));

	return temp;
}
 
Example 5
Source File: Transform.java    From FTCVision with MIT License 6 votes vote down vote up
/**
 * Rotate an image by an angle (counterclockwise)
 *
 * @param image Transform matrix
 * @param angle Angle to rotate by (counterclockwise) from -360 to 360
 */
public static void rotate(Mat image, double angle) {
    //Calculate size of new matrix
    double radians = Math.toRadians(angle);
    double sin = Math.abs(Math.sin(radians));
    double cos = Math.abs(Math.cos(radians));

    int newWidth = (int) (image.width() * cos + image.height() * sin);
    int newHeight = (int) (image.width() * sin + image.height() * cos);

    // rotating image
    Point center = new Point(newWidth / 2, newHeight / 2);
    Mat rotMatrix = Imgproc.getRotationMatrix2D(center, angle, 1.0); //1.0 means 100 % scale

    Size size = new Size(newWidth, newHeight);
    Imgproc.warpAffine(image, image, rotMatrix, image.size());
}
 
Example 6
Source File: FindAttributes.java    From SikuliX1 with MIT License 5 votes vote down vote up
private Mat possibleImageResizeMask(Image image, Mat what) {
  Mat mask = image.getMask().getContent();
  double factor = mask.width() / what.width();
  if (factor > 0.1 && factor != 1) {
    mask = SXOpenCV.cvResize(mask.clone(), factor, Image.Interpolation.CUBIC);
  }
  List<Mat> mats = SXOpenCV.extractMask(mask, false);
  return mats.get(1);
}
 
Example 7
Source File: SXTest.java    From SikuliX1 with MIT License 5 votes vote down vote up
public static void showCV(Mat image) {
  String title = "show Mat";
  HighGui.namedWindow(title);
  Screen screen = Screen.getPrimaryScreen();
  int x = (screen.w - image.width()) / 2;
  int y = (screen.h - image.height()) / 2;
  HighGui.moveWindow(title, x, y);
  HighGui.imshow(title, image);
  HighGui.waitKey(3000);
}
 
Example 8
Source File: ImageProcessor.java    From react-native-documentscanner-android with MIT License 5 votes vote down vote up
public Result[] zxing( Mat inputImage ) throws ChecksumException, FormatException {

        int w = inputImage.width();
        int h = inputImage.height();

        Mat southEast;

        if (mBugRotate) {
            southEast = inputImage.submat(h-h/4 , h , 0 , w/2 - h/4 );
        } else {
            southEast = inputImage.submat(0, h / 4, w / 2 + h / 4, w);
        }

        Bitmap bMap = Bitmap.createBitmap(southEast.width(), southEast.height(), Bitmap.Config.ARGB_8888);
        org.opencv.android.Utils.matToBitmap(southEast, bMap);
        southEast.release();
        int[] intArray = new int[bMap.getWidth()*bMap.getHeight()];
        //copy pixel data from the Bitmap into the 'intArray' array
        bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());

        LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(),intArray);

        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        Result[] results = {};
        try {
            results = qrCodeMultiReader.decodeMultiple(bitmap);
        }
        catch (NotFoundException e) {
        }

        return results;

    }
 
Example 9
Source File: FindPassword.java    From SoftwarePilot with MIT License 5 votes vote down vote up
FPClassification findAngles(Mat image, Rect rect){
		double imageCenterX = (image.width()/2);
		double faceCenterX = rect.x + (rect.width/2);
		double distanceFromCenterX = Math.abs(imageCenterX - faceCenterX);
		double angleX = (distanceFromCenterX/imageCenterX) * CAMERA_FOV_VERT/2;

		System.out.println("Image CenterX: "+imageCenterX +
				   "\nRect X: "+rect.x +
				   "\nRect Width: "+rect.width +
				   "\nFace Center: "+faceCenterX+
				   "\nDistance From Center: "+distanceFromCenterX+
				   "\nAngle: "+angleX);

		double imageCenterY = (image.height()/2);
		double faceCenterY = rect.y + (rect.height/2);
		double distanceFromCenterY = Math.abs(imageCenterY - faceCenterY);
		double angleY = (distanceFromCenterY/imageCenterY) * CAMERA_FOV_HORIZ/2;

		System.out.println("Image CenterY: "+imageCenterY +
				   "\nRect Y: "+rect.y +
				   "\nRect Height: "+rect.height +
				   "\nFace Center: "+faceCenterY+
				   "\nDistance From Center: "+distanceFromCenterY+
				   "\nAngle: "+angleY);

		FPClassification ret = new FPClassification();
		ret.angleX = angleX;
		ret.angleY = angleY;
		ret.detected = true;

		if(imageCenterX > rect.x)
			ret.angleX *= -1;
		if(imageCenterY < rect.y)
			ret.angleY *= -1;
		return ret;
}
 
Example 10
Source File: MathUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * 把opencv的灰度图Mat转化为List<List<Double>> , 即数组对象
 * 
 * @param gray
 * @param b
 *            true 表示List<Double>是每一列的灰度值,否则List<Double>是每一行的灰度值
 * @return
 */
public static List<List<Double>> MatPixelToList(Mat gray, boolean b) {
	if (gray == null) {
		throw new RuntimeException("不能传入空对象");
	}
	List<List<Double>> result = new ArrayList<>();
	int x, y;
	int i, j;
	double[] value;
	if (b) {
		// List<Double>是每一列的灰度值
		x = gray.width();
		y = gray.height();
	} else {
		// List<Double>是每一行的灰度值
		x = gray.height();
		y = gray.width();
	}

	for (i = 0; i < x; i++) {
		List<Double> oneLine = new ArrayList<>();
		for (j = 0; j < y; j++) {
			if (b) {
				value = gray.get(j, i);
			} else {
				value = gray.get(i, j);
			}

			oneLine.add(value[0]);
		}
		result.add(oneLine);
	}

	return result;
}
 
Example 11
Source File: ImageUtils.java    From justtestlah with Apache License 2.0 5 votes vote down vote up
/**
 * @param image the {@link Mat} to scale
 * @param scaleFactor the scale factor (&lt;1 will scale down, &gt;1 will scale up, 1 = 100%)
 * @return a {@link Mat} which is a version of the original image scaled by the given factor
 */
public static Mat scaleImage(Mat image, double scaleFactor) {
  Mat resizedImage = new Mat();
  Size sz = new Size(image.width() * scaleFactor, image.height() * scaleFactor);
  Imgproc.resize(image, resizedImage, sz);
  return resizedImage;
}
 
Example 12
Source File: Camera.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
static BufferedImage matToBufferedImage(Mat matBGR) {
	final BufferedImage image = new BufferedImage(matBGR.width(), matBGR.height(), BufferedImage.TYPE_3BYTE_BGR);
	final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
	matBGR.get(0, 0, targetPixels);

	return image;
}
 
Example 13
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 14
Source File: ImageProcessor.java    From Document-Scanner with GNU General Public License v3.0 5 votes vote down vote up
public Result[] zxing( Mat inputImage ) throws ChecksumException, FormatException {

        int w = inputImage.width();
        int h = inputImage.height();

        Mat southEast;

        if (mBugRotate) {
            southEast = inputImage.submat(h-h/4 , h , 0 , w/2 - h/4 );
        } else {
            southEast = inputImage.submat(0, h / 4, w / 2 + h / 4, w);
        }

        Bitmap bMap = Bitmap.createBitmap(southEast.width(), southEast.height(), Bitmap.Config.ARGB_8888);
        org.opencv.android.Utils.matToBitmap(southEast, bMap);
        southEast.release();
        int[] intArray = new int[bMap.getWidth()*bMap.getHeight()];
        //copy pixel data from the Bitmap into the 'intArray' array
        bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());

        LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), bMap.getHeight(),intArray);

        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        Result[] results = {};
        try {
            results = qrCodeMultiReader.decodeMultiple(bitmap);
        }
        catch (NotFoundException ignored) {
        }
        return results;
    }
 
Example 15
Source File: TLDView.java    From OpenTLDAndroid with Apache License 2.0 4 votes vote down vote up
@Override
public Mat onCameraFrame(Mat originalFrame) {
	try{
		// Image is too big and this requires too much CPU for a phone, so scale everything down...
		Imgproc.resize(originalFrame, _workingFrame, WORKING_FRAME_SIZE);
		final Size workingRatio = new Size(originalFrame.width() / WORKING_FRAME_SIZE.width, originalFrame.height() / WORKING_FRAME_SIZE.height);
		// usefull to see what we're actually working with...
		_workingFrame.copyTo(originalFrame.submat(originalFrame.rows() - _workingFrame.rows(), originalFrame.rows(), 0, _workingFrame.cols()));
		
		if(_trackedBox != null){
			if(_tld == null){ // run the 1st time only
				Imgproc.cvtColor(_workingFrame, _lastGray, Imgproc.COLOR_RGB2GRAY);
				_tld = new Tld(_tldProperties);
				final Rect scaledDownTrackedBox = scaleDown(_trackedBox, workingRatio);
				Log.i(Util.TAG, "Working Ration: " + workingRatio + " / Tracking Box: " + _trackedBox + " / Scaled down to: " + scaledDownTrackedBox);
				try {
					_tld.init(_lastGray, scaledDownTrackedBox);
				}catch(Exception eInit){
			        // start from scratch, you have to select an init box again !
					_trackedBox = null;
					_tld = null;
					throw eInit; // re-throw it as it will be dealt with later
				}
			}else{
				Imgproc.cvtColor(_workingFrame, _currentGray, Imgproc.COLOR_RGB2GRAY);
			
				_processFrameStruct = _tld.processFrame(_lastGray, _currentGray);
				drawPoints(originalFrame, _processFrameStruct.lastPoints, workingRatio, new Scalar(255, 0, 0));
				drawPoints(originalFrame, _processFrameStruct.currentPoints, workingRatio, new Scalar(0, 255, 0));
				drawBox(originalFrame, scaleUp(_processFrameStruct.currentBBox, workingRatio), new Scalar(0, 0, 255));
					
				_currentGray.copyTo(_lastGray);
				
				// overlay the current positive examples on the real image(needs converting at the same time !)
				//copyTo(_tld.getPPatterns(), originalFrame);
			}
		}
	} catch(Exception e) {
        _errMessage = e.getClass().getSimpleName() + " / " + e.getMessage();
        Log.e(Util.TAG, "TLDView PROBLEM", e);
	}

	
	if(_errMessage !=  null){
		Core.putText(originalFrame, _errMessage, new Point(0, 300), Core.FONT_HERSHEY_PLAIN, 1.3d, new Scalar(255, 0, 0), 2);
	}
	
       return originalFrame;
}
 
Example 16
Source File: ImgWindow.java    From opencv-fun with GNU Affero General Public License v3.0 4 votes vote down vote up
public static BufferedImage matToBufferedImage (Mat matrix) {		
	if (matrix.channels() == 1) {
		int cols = matrix.cols();
		int rows = matrix.rows();
		int elemSize = (int)matrix.elemSize();
		byte[] data = new byte[cols * rows * elemSize];
		int type;
		matrix.get(0, 0, data);
		switch (matrix.channels()) {
		case 1:
			type = BufferedImage.TYPE_BYTE_GRAY;
			break;
		case 3:
			type = BufferedImage.TYPE_3BYTE_BGR;
			// bgr to rgb
			byte b;
			for (int i = 0; i < data.length; i = i + 3) {
				b = data[i];
				data[i] = data[i + 2];
				data[i + 2] = b;
			}
			break;
		default:
			return null;
		}

		BufferedImage image2 = new BufferedImage(cols, rows, type);
		image2.getRaster().setDataElements(0, 0, cols, rows, data);
		return image2;
	}

	if (matrix.channels() == 3) {
		int width = matrix.width(), height = matrix.height(), channels = matrix.channels();
		byte[] sourcePixels = new byte[width * height * channels];
		matrix.get(0, 0, sourcePixels);
		// create new image and get reference to backing data
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		final byte[] targetPixels = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
		System.arraycopy(sourcePixels, 0, targetPixels, 0, sourcePixels.length);
		return image;
	}

	return null;
}
 
Example 17
Source File: Proc.java    From android-object-distance with Apache License 2.0 4 votes vote down vote up
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 18
Source File: MainActivity.java    From effective_android_sample with Apache License 2.0 4 votes vote down vote up
/**
 * OpenCVで
 * @param bmpOrig
 */
private void extractObject(Bitmap bmpOrig) {

    // まずオリジナルのビットマップを表示
    mImageView1.setImageBitmap(bmpOrig);
    // 高さと幅を取得
    int height = bmpOrig.getHeight();
    int width = bmpOrig.getWidth();
    
    // OpenCVオブジェクトの用意
    Mat matOrig = new Mat(height,width,CvType.CV_8UC4); 
    // ビットマップをOpenCVオブジェクトに変換
    Utils.bitmapToMat(bmpOrig, matOrig);
    
    /**
     * グレースケールに変換
     */
    Mat matGray = new Mat(height,width,CvType.CV_8UC1);
    Imgproc.cvtColor(matOrig, matGray, Imgproc.COLOR_RGB2GRAY);
    // 表示
    Bitmap bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(matGray, bmpGray);
    mImageView2.setImageBitmap(bmpGray);

    /**
     * グレースケール→二値化    
     */
    Mat matBlack = new Mat(height,width,CvType.CV_8UC1);
    // 二値化
    Imgproc.threshold(matGray, matBlack, sTH, 255, Imgproc.THRESH_BINARY);
    // 表示
    Bitmap bmpBlack = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(matBlack, bmpBlack);
    mImageView3.setImageBitmap(bmpBlack);

    /**
     * グレースケール→二値化→輪郭塗りつぶし
     */
    // 輪郭を抽出する
    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy = new Mat(matBlack.height(),matBlack.width(),CvType.CV_8UC1);
    int mode = Imgproc.RETR_EXTERNAL;
    int method = Imgproc.CHAIN_APPROX_SIMPLE;

    // 輪郭を抽出する
    Imgproc.findContours(matBlack, contours, hierarchy, mode, method);
    // 輪郭を描く
    Scalar color = new Scalar(255.f, 0.f, 0.f, 0.f);
    Imgproc.drawContours(matBlack, contours, -1, color, 2);
    // 表示
    Bitmap bmpContour = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matBlack, bmpContour);
    mImageView4.setImageBitmap(bmpContour);

    // 抽出した輪郭の内部を塗りつぶす
    Imgproc.drawContours(matBlack, contours, -1, color, -1);
    // 表示
    Bitmap bmpContour2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matBlack, bmpContour2);
    mImageView5.setImageBitmap(bmpContour2);

    
    /**
     * 二値化したマスクを使ってオブジェクトだけをとりだす
     */
    Mat matObject = new Mat(height,width,CvType.CV_8UC4); 
    Core.add(matObject, matOrig, matObject, matBlack);  
    // 表示
    Bitmap bmpObject = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matObject, bmpObject);
    mImageView6.setImageBitmap(bmpObject);

    /**
     * とりだしたオブジェクトに外接する矩形のみをBMPとして抜き出す
     */
    Rect rect = Imgproc.boundingRect(contours.get(0));
    Mat matCut = new Mat(matObject, rect);
    // 表示
    Bitmap bmpCut = Bitmap.createBitmap(matCut.cols(), matCut.rows(), Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matCut, bmpCut);
    mImageView7.setImageBitmap(bmpCut);
}
 
Example 19
Source File: ImageFinder.java    From opentest with MIT License 4 votes vote down vote up
/**
 * Finds a template image in a source image. Throws an exception when the
 * image wasn't found or the desired accuracy couldn't be met.
 *
 * @param sourceMat The source image.
 * @param templateMat The template image to find in the source image.
 * @param desiredAccuracy The desired accuracy of the find operation as a
 * number between 0 and 1.
 * @return An ImageFinderResult object that stores the rectangle of the
 * found image and desired accuracy.
 */
private ImageFinderResult findImage(Mat sourceMat, Mat templateMat, double desiredAccuracy) {
    if (sourceMat.width() < templateMat.width() || sourceMat.height() < templateMat.height()) {
        throw new UnsupportedOperationException("The template image is larger than the source image. Ensure that the width and/or height of the image you are trying to find do not exceed the dimensions of the source image.");
    }

    Mat result = new Mat(sourceMat.rows() - templateMat.rows() + 1, sourceMat.rows() - templateMat.rows() + 1, CvType.CV_32FC1);
    int intMatchingMethod;

    switch (this.matchingMethod) {
        case MM_CORELLATION_COEFF:
            intMatchingMethod = Imgproc.TM_CCOEFF_NORMED;
            break;
        case MM_CROSS_CORELLATION:
            intMatchingMethod = Imgproc.TM_CCORR_NORMED;
            break;
        default:
            intMatchingMethod = Imgproc.TM_SQDIFF_NORMED;
    }

    Imgproc.matchTemplate(sourceMat, templateMat, result, intMatchingMethod);
    MinMaxLocResult minMaxLocRes = Core.minMaxLoc(result);

    double accuracy = 0;
    Point location = null;

    if (this.matchingMethod == MatchingMethod.MM_SQUARE_DIFFERENCE) {
        accuracy = 1 - minMaxLocRes.minVal;
        location = minMaxLocRes.minLoc;
    } else {
        accuracy = minMaxLocRes.maxVal;
        location = minMaxLocRes.maxLoc;
    }

    if (accuracy < desiredAccuracy) {
        throw new ImageNotFoundException(
                String.format(
                        "Failed to find template image in the source image. The accuracy was %.2f and the desired accuracy was %.2f",
                        accuracy,
                        desiredAccuracy),
                new Rectangle((int) location.x, (int) location.y, templateMat.width(), templateMat.height()),
                accuracy);
    }

    if (!minMaxLocResultIsValid(minMaxLocRes)) {
        throw new ImageNotFoundException(
                "Image find result (MinMaxLocResult) was invalid. This usually happens when the source image is covered in one solid color.",
                null,
                null);
    }

    Rectangle foundRect = new Rectangle(
            (int) location.x,
            (int) location.y,
            templateMat.width(),
            templateMat.height());

    return new ImageFinderResult(foundRect, accuracy);
}
 
Example 20
Source File: CutUtils.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
/**
 * 切割
 * 
 * @param src
 * @return
 */
public static List<Mat> cutUtils(Mat src) {
	if (src.channels() != 1) {
		src = GrayUtils.grayColByPartAdapThreshold(src);
		src = BinaryUtils.binaryzation(src);
	}

	if (src.height() > src.width()) {
		src = RotationUtils.rotation(src);
	}

	// 求最大轮廓的点集
	Point[] points = ContoursUtils.useApproxPolyDPFindPoints(GeneralUtils.canny(src));

	src = PaintUtils.paintCircle(src, points, 10, new Scalar(255, 255, 255));

	// 清除最大的连通域
	src = RemoveNoiseUtils.findMaxConnected(src, 255);

	// 降噪
	src = RemoveNoiseUtils.connectedRemoveNoise(src, 100);

	// 水平切割
	List<Mat> xList = cutUtilsX(src);

	// 垂直切割
	List<Integer> yPoint = cutUtilsY(xList.get(0));

	// 最终的结果集
	List<Mat> result = new ArrayList<>();

	int xlen = xList.size();
	for (int i = 0; i < xlen; i++) {
		if (xlen > 1 && i == 0) {
			continue;
		}
		for (int j = 1; j < yPoint.size(); j++) {
			Mat temp = new Mat(xList.get(i),
					new Rect(yPoint.get(j - 1), 0, yPoint.get(j) - yPoint.get(j - 1), xList.get(i).height()));
			result.add(temp);
		}

	}

	return result;

}