Java Code Examples for org.opencv.highgui.Highgui#imread()

The following examples show how to use org.opencv.highgui.Highgui#imread() . 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 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 = 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: HistogramEqualization.java    From opencv-fun with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void main (String[] args) {
	CVLoader.load();
	
	// load the image
	Mat img = Highgui.imread("data/topdown-9.png");
	Mat equ = new Mat();
	img.copyTo(equ);
	Imgproc.blur(equ, equ, new Size(3, 3));
	
	Imgproc.cvtColor(equ, equ, Imgproc.COLOR_BGR2YCrCb);
	List<Mat> channels = new ArrayList<Mat>();
	Core.split(equ, channels);
	Imgproc.equalizeHist(channels.get(0), channels.get(0));
	Core.merge(channels, equ);
	Imgproc.cvtColor(equ, equ, Imgproc.COLOR_YCrCb2BGR);
	
	Mat gray = new Mat();
	Imgproc.cvtColor(equ, gray, Imgproc.COLOR_BGR2GRAY);
	Mat grayOrig = new Mat();
	Imgproc.cvtColor(img, grayOrig, Imgproc.COLOR_BGR2GRAY);
	
	ImgWindow.newWindow(img);
	ImgWindow.newWindow(equ);
	ImgWindow.newWindow(gray);
	ImgWindow.newWindow(grayOrig);
}
 
Example 3
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取人脸范围
 * @param fileName
 * @return
 */
public static MatOfRect takeFace(String fileName) {
    CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml");
    Mat image = Highgui.imread(fileName);
    MatOfRect faceDetections = new MatOfRect();
    // 指定人脸识别的最大和最小像素范围
    Size minSize = new Size(120, 120);
    Size maxSize = new Size(250, 250);
    // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率
    faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0,
            minSize, maxSize);
    return faceDetections;
}
 
Example 4
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * 二值化
 *
 * @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 5
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * 边缘检测的原理:检测出图像中所有灰度值变化较大的点,而且这些点连起来构成若干线条,这些线条就称之为图像的边缘。
 * @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 6
Source File: BallDetection.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main (String[] args) {
	CVLoader.load();
	
	ImgWindow wnd = ImgWindow.newWindow();
	Calibration calib = new Calibration(1280, 800);
	calib.setBackgroundImage(Highgui.imread("screenshots/positions/background.png"));
	BallDetector detector = new BallDetector(calib);
	Mat camera = Highgui.imread("screenshots/positions/camera.png");
	
	 while(true) {
		 detect(wnd, detector, camera);
	 }
}
 
Example 7
Source File: HoughCircles.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main (String[] args) {
		CVLoader.load();
		Mat orig = Highgui.imread("data/topdown-6.jpg");
		Mat gray = new Mat();
		orig.copyTo(gray);
		
		// blur
//		Imgproc.medianBlur(gray, gray, 5);
//		Imgproc.GaussianBlur(gray, gray, new Size(3, 3), 100);
		
		// convert to grayscale
		Imgproc.cvtColor(gray, gray, Imgproc.COLOR_BGR2GRAY);
		
		// do hough circles
		Mat circles = new Mat();
		int minRadius = 10;
		int maxRadius = 18;
		Imgproc.HoughCircles(gray, circles, Imgproc.CV_HOUGH_GRADIENT, 1, minRadius, 120, 10, minRadius, maxRadius);
		System.out.println(circles);
		
		ImgWindow.newWindow(gray);
		ImgWindow wnd = ImgWindow.newWindow(orig);			
		
		while(!wnd.closed) {
			wnd.setImage(orig);
			Graphics2D g = wnd.begin();
			g.setColor(Color.MAGENTA);
			g.setStroke(new BasicStroke(3));
			for(int i = 0; i < circles.cols(); i++) {
				double[] circle = circles.get(0, i);
				g.drawOval((int)circle[0] - (int)circle[2], (int)circle[1] - (int)circle[2], (int)circle[2] * 2, (int)circle[2] * 2);
			}		
			wnd.end();
		}
	}
 
Example 8
Source File: HoughLines.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main (String[] args) {
	CVLoader.load();
	
	// load the image
	Mat img = Highgui.imread("data/topdown-6.jpg");
	
	// generate gray scale and blur
	Mat gray = new Mat();
	Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY);
	Imgproc.blur(gray, gray, new Size(3, 3));
	
	// detect the edges
	Mat edges = new Mat();
	int lowThreshold = 50;
	int ratio = 3;
	Imgproc.Canny(gray, edges, lowThreshold, lowThreshold * ratio);
	
	Mat lines = new Mat();
	Imgproc.HoughLinesP(edges, lines, 1, Math.PI / 180, 50, 50, 10);
	
	for(int i = 0; i < lines.cols(); i++) {
		double[] val = lines.get(0, i);
		Core.line(img, new Point(val[0], val[1]), new Point(val[2], val[3]), new Scalar(0, 0, 255), 2);
	}
	
	ImgWindow.newWindow(edges);
	ImgWindow.newWindow(gray);
	ImgWindow.newWindow(img);
}
 
Example 9
Source File: IpCamera.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public IpCamera(final String url) {
	this.frame = Mat.zeros(new Size(200, 200), CvType.CV_8UC3);
	this.url = url;
	thread = new Thread(new Runnable() {
		@Override
		public void run () {
			while(true) {
				try {
					ByteArrayOutputStream bytes = new ByteArrayOutputStream();
					byte[] buffer = new byte[10 * 1024];
					URLConnection con = new URL(url + "/shot.jpg").openConnection();
					InputStream in = con.getInputStream();
					int read = -1;
					while((read = in.read(buffer)) != -1) {
						bytes.write(buffer, 0, read);
					}
					DataOutputStream writer = new DataOutputStream(new FileOutputStream(new File("img.jpg")));
					writer.write(bytes.toByteArray());
					writer.close();
					Mat mat =  Highgui.imread("img.jpg");
					synchronized(this) {
						frame = mat;
					}
				} catch(Throwable t) {
					t.printStackTrace();
				}
			}
		}
	});
	thread.setDaemon(true);
	thread.start();
}
 
Example 10
Source File: FaceDetectionActivity.java    From AndroidFaceRecognizer with MIT License 5 votes vote down vote up
private void setImagesForDatabaseEdit() {
	for(int i = 0; i < faceImages.size(); i++) {
		Mat m = Highgui.imread(thisPerson.getFacesFolderPath()+"/"+i+".jpg");
		if(m != null) {
			onFaceCaptured(m);
		}
	}
}
 
Example 11
Source File: WeightedStandardPixelTrainer.java    From GenderRecognizer with MIT License 4 votes vote down vote up
public static void main(String[] args) {
	System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	
	//list of image files//////////////////////////////////////////////////////////////////////////////////////////
	/*String[] stringFilePaths = {"resource/Face_Male_Female/images1", "resource/Face_Male_Female/images2"};
	
	ArrayList<String> filePathList = new ArrayList<String>();
	ArrayList<Integer> idList = new ArrayList<Integer>();
	
	int id=0;
	for(String stringFilePath: stringFilePaths){
		
		File[] files = new File(stringFilePath).listFiles();
		
		for(File file: files){
			filePathList.add(file.getAbsolutePath());
			idList.add(id);
		}
		
		id++;
	}
	
	String[] filePaths = new String[filePathList.size()];
	filePathList.toArray(filePaths);
	Integer[] ids = new Integer[idList.size()];
	idList.toArray(ids);
	*/
	
	///test
	/*for(int i=filePaths.length-1; i>=0; i--){
		System.out.println("filePaths: " + filePaths[i]);
		System.out.println("ids: " + ids[i]);
	}*/
	
	
	//train and predict////////////////////////////////////////////////////////////////////////////////////////////
	WeightedStandardPixelTrainer weightedStandardPixelTrainer = new WeightedStandardPixelTrainer();
	/*weightedStandardPixelTrainer.train(filePaths, ids);
	WeightedStandardImage weightedStandardImage = weightedStandardPixelTrainer.getWeightedStandardImage();
	weightedStandardImage.saveKnowledge("resource/Face_Male_Female/Knowledge.log");*/
	//experience file
	weightedStandardPixelTrainer.load("res/knowledge/KnowledgeAlphabet.log");
	/*WeightedStandardImage weightedStandardImage = weightedStandardPixelTrainer.getWeightedStandardImage();
	System.out.println(weightedStandardImage.dump());*/
	
	//sample file
	String imageFilePath = "C:\\Users\\admin\\Desktop\\1.jpg";
	Mat mat = Highgui.imread(imageFilePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
	
	int prediction = weightedStandardPixelTrainer.predict(mat);
	System.out.println("Prediction is: " + prediction);
	
	
	/*Mat mat = weightedStandardImage.getStandardImages(0);
	Highgui.imwrite("resource/Face_Male_Female/stdImage4.png" , mat);*/
	
	System.out.println("Operation Successful!!!");
}
 
Example 12
Source File: LoadImage.java    From opencv-fun with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void main (String[] args) {
	CVLoader.load();
	Mat img = Highgui.imread("data/topdown-1.jpg", Highgui.CV_LOAD_IMAGE_COLOR);
	ImgWindow window = ImgWindow.newWindow(img);
}
 
Example 13
Source File: Test.java    From GenderRecognizer with MIT License 4 votes vote down vote up
public static void main(String[] args) {
	System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	
	WeightedStandardPixelTrainer weightedStandardPixelTrainer = new WeightedStandardPixelTrainer();
	weightedStandardPixelTrainer.load("src/res/knowledge/Knowledge.log");

	//sample file
	String testFolderPath = "src/res/trainingData";
	
	File testFolder = new File(testFolderPath);
	String[] testSubfolderPaths = testFolder.list(new FilenameFilter() {
	  @Override
	  public boolean accept(File current, String name) {
	    return new File(current, name).isDirectory();
	  }
	});
	

	int id=0;	//label
	int right=0;
	int wrong=0;
	for(String SubfolderPath: testSubfolderPaths){
		File[] files = new File(testFolderPath+"\\"+SubfolderPath).listFiles();
		
		for(File file: files){
			String imageFilePath = file.getAbsolutePath();
			Mat mat = Highgui.imread(imageFilePath, Highgui.IMREAD_GRAYSCALE);
			
			int prediction = weightedStandardPixelTrainer.predict(mat);
			
			if(prediction==id){
				right++;
				System.out.print("R");
			}else{
				wrong++;
				System.out.println("W");
			}
		}
		
		id++;
	}
	
	System.out.println("Percentage of error: " + wrong*100/(wrong+right));
	
	System.out.println("Operation Successful!!!");
}
 
Example 14
Source File: KMeansMatcher.java    From mvisc with GNU General Public License v3.0 4 votes vote down vote up
public void computeModel(ArrayList<MetaData> photos)
{
	numPhotos = photos.size();
	model.setNumPhotos(numPhotos);

	MatOfKeyPoint[] keypoints = new MatOfKeyPoint[numPhotos];
	Mat[] descriptors = new Mat[numPhotos];
	Mat allDescriptors = new Mat();
	ArrayList<Integer> descriptorLabels = new ArrayList<Integer>();

	// compute keypoints and descriptors
	Mat currentImg = null;
	for (int a = 0; a < numPhotos; a++)
	{
		// System.out.println("now:" + animalFiles.get(a));
		currentImg = Highgui.imread(photos.get(a).getZooName().toString(), 0);
		Imgproc.resize(currentImg, currentImg, new Size(150, 250));
		Imgproc.equalizeHist(currentImg, currentImg);
		Imgproc.threshold(currentImg, currentImg, 127, 255, Imgproc.THRESH_BINARY);

		featureDetector.detect(currentImg, keypoints[a]);
		descriptorExtractor.compute(currentImg, keypoints[a], descriptors[a]);

		allDescriptors.push_back(descriptors[a]);

		for (int i = 0; i < descriptors[a].rows(); i++)
			descriptorLabels.add(a);
	}
	System.out.println("label size:" + descriptorLabels.size());

	Mat clusterLabels = new Mat();
	Mat centers = new Mat();

	// set up all desriptors, init criteria
	allDescriptors.convertTo(allDescriptors, CvType.CV_32F);
	TermCriteria criteria = new TermCriteria(TermCriteria.EPS + TermCriteria.MAX_ITER, 100, 0.1);
	long before = System.currentTimeMillis();
	
	// compute clusters
	System.out.print("creating kmeans clusters...");
	Core.kmeans(allDescriptors, k, clusterLabels, criteria, 10, Core.KMEANS_PP_CENTERS, centers);
	System.out.println("done.");

	// map k-means centroid labels to descriptors of all images
	ArrayList<ArrayList<Integer>> clusterImageMap = new ArrayList<ArrayList<Integer>>();
	for (int nk = 0; nk < k + 1; nk++)
		clusterImageMap.add(new ArrayList<Integer>());
	for (int r = 0; r < clusterLabels.rows(); r++)
		clusterImageMap.get((int) clusterLabels.get(r, 0)[0]).add(descriptorLabels.get(r));

	model.setCentroids(centers);
	model.setLabels(clusterLabels);
	model.setClusterImageMap(clusterImageMap);
	model.setKeypoints(keypoints);
	model.setDescriptors(descriptors);

}
 
Example 15
Source File: WeightedStandardPixelTrainer.java    From GenderRecognizer with MIT License 4 votes vote down vote up
/**
 * 
 * @param imageFilePaths
 * @param ids
 * @return
 */
public void train(String[] imageFilePaths, Integer[] ids){
	if(imageFilePaths.length!=ids.length){	//data check
		System.out.println("Incompatible data.");
		return ;
	}
	
	int[] variety = varietyIn(ids);
	int types = variety[variety.length-1];
	int standardImageRow = (int)imageSize.width, standardImageCol = (int)imageSize.height;
	WeightedStandardImage weightedStandardImage = new WeightedStandardImage(types, imageSize);
	
	
	for(int i=0; i<types; i++){
		weightedStandardImage.setId(i, variety[i]);
	}
	
	
	Mat mat;
	int typeNo=0, index=0;
	for(String imageFilePath : imageFilePaths){
		mat = Highgui.imread(imageFilePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
		Imgproc.resize(mat, mat, imageSize);
		mat = toMedial(mat);
		
		double sumValue = 0;
		int value=0;
		
		for(int i=0; i<types; i++){
			if(weightedStandardImage.getId(i)==ids[index]){
				typeNo=i;
				break;
			}
		}
		
		for(int row=0; row<standardImageRow; row++){
			for(int col=0; col<standardImageCol; col++){
				sumValue = (weightedStandardImage.getStandardImages(typeNo, row, col) *
						weightedStandardImage.getWeight(typeNo)) +
						mat.get(row, col)[0];
				
				value = (int) sumValue / (weightedStandardImage.getWeight(typeNo)+1);
				
				weightedStandardImage.setStandardImages(typeNo, row, col, (short) value);
			}
		}
		
		weightedStandardImage.incrementWeight(typeNo);
		System.out.println(index + ": image No: " + weightedStandardImage.getWeight(typeNo));	//show progress
		
		index++;
	}
	
	this.weightedStandardImage = weightedStandardImage;
	
	return ;
}
 
Example 16
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 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: KMeansMatcher.java    From mvisc with GNU General Public License v3.0 4 votes vote down vote up
public void setQueryImage(MetaData metaData)
{
	this.queryImage = Highgui.imread(metaData.getZooName().toString(), 0);
}