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

The following examples show how to use org.opencv.core.Mat#clone() . 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: HSVColorFilter.java    From DogeCV with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Process a image and return a mask
 * @param input - Input image to process
 * @param mask - Output mask
 */
@Override
public void process(Mat input, Mat mask) {
    // Copy the input to working mat
    workingMat = input.clone();
    // Convert the input to HSV color space
    Imgproc.cvtColor(workingMat,workingMat,Imgproc.COLOR_RGB2HSV_FULL);

    // Blur the imgae
    Imgproc.GaussianBlur(workingMat,workingMat,new Size(5,5),0);

    // Run a inRange mask using the color and range
    Scalar lower = new Scalar(perfect.val[0] - (range.val[0]/2), perfect.val[1] - (range.val[1]/2),perfect.val[2] - (range.val[2]/2));
    Scalar upper = new Scalar(perfect.val[0] + (range.val[0]/2), perfect.val[1] + (range.val[1]/2),perfect.val[2] + (range.val[2]/2));
    Core.inRange(workingMat,lower,upper,mask);
}
 
Example 2
Source File: ALTMRetinex.java    From OptimizedImageEnhance with MIT License 6 votes vote down vote up
private static List<Mat> globalAdaptation(Mat b, Mat g, Mat r, int rows, int cols) {
	// Calculate Lw & maximum of Lw
	Mat Lw = new Mat(rows, cols, r.type());
	Core.multiply(r, new Scalar(rParam), r);
	Core.multiply(g, new Scalar(gParam), g);
	Core.multiply(b, new Scalar(bParam), b);
	Core.add(r, g, Lw);
	Core.add(Lw, b, Lw);
	double LwMax = Core.minMaxLoc(Lw).maxVal; // the maximum luminance value
	// Calculate log-average luminance and get global adaptation result
	Mat Lw_ = Lw.clone();
	Core.add(Lw_, new Scalar(0.001), Lw_);
	Core.log(Lw_, Lw_);
	double LwAver = Math.exp(Core.sumElems(Lw_).val[0] / (rows * cols));
	Mat Lg = Lw.clone();
	Core.divide(Lg, new Scalar(LwAver), Lg);
	Core.add(Lg, new Scalar(1.0), Lg);
	Core.log(Lg, Lg);
	Core.divide(Lg, new Scalar(Math.log(LwMax / LwAver + 1.0)), Lg); // Lg is the global adaptation
	List<Mat> list = new ArrayList<>();
	list.add(Lw);
	list.add(Lg);
	return list;
}
 
Example 3
Source File: VideoMotionDetector.java    From video-stream-analytics with Apache License 2.0 6 votes vote down vote up
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 4
Source File: PaintUtils.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 *
 * 画出所有的矩形
 * 
 * @param src
 * @return
 */
public static Mat paintCon(Mat src) {
	Mat cannyMat = GeneralUtils.canny(src);
	List<MatOfPoint> contours = ContoursUtils.findContours(cannyMat);

	Mat rectMat = src.clone();
	Scalar scalar = new Scalar(0, 0, 255);
	for (int i = contours.size() - 1; i >= 0; i--) {
		MatOfPoint matOfPoint = contours.get(i);
		MatOfPoint2f matOfPoint2f = new MatOfPoint2f(matOfPoint.toArray());

		RotatedRect rect = Imgproc.minAreaRect(matOfPoint2f);

		Rect r = rect.boundingRect();

		System.out.println(r.area() + " --- " + i);

		rectMat = paintRect(rectMat, r, scalar);

	}

	return rectMat;
}
 
Example 5
Source File: FusionEnhance.java    From OptimizedImageEnhance with MIT License 6 votes vote down vote up
private static Mat calWeight(Mat img, Mat L) {
	Core.divide(L, new Scalar(255.0), L);
	L.convertTo(L, CvType.CV_32F);
	// calculate laplacian contrast weight
	Mat WL = FeatureWeight.LaplacianContrast(L);
	WL.convertTo(WL, L.type());
	// calculate Local contrast weight
	Mat WC = FeatureWeight.LocalContrast(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 = WL.clone();
	Core.add(weight, WC, weight);
	Core.add(weight, WS, weight);
	Core.add(weight, WE, weight);
	return weight;
}
 
Example 6
Source File: Pyramid.java    From ImageEnhanceViaFusion with MIT License 6 votes vote down vote up
public static Mat[] LaplacianPyramid(Mat img, int level) {
	Mat[] lapPyr = new Mat[level];
	//Mat mask = filterMask(img);
	lapPyr[0] = img.clone();
	Mat tmpImg = img.clone();
	for (int i = 1; i < level; i++) {
		// resize image
		Imgproc.resize(tmpImg, tmpImg, new Size(), 0.5, 0.5, Imgproc.INTER_LINEAR);
		lapPyr[i] = tmpImg.clone();
	}
	// calculate the DoG
	for (int i = 0; i < level - 1; i++) {
		Mat tmpPyr = new Mat();
		Imgproc.resize(lapPyr[i + 1], tmpPyr, lapPyr[i].size(), 0, 0, Imgproc.INTER_LINEAR);
		Core.subtract(lapPyr[i], tmpPyr, lapPyr[i]);
	}
	return lapPyr;
}
 
Example 7
Source File: EnhanceFunc.java    From ImageEnhanceViaFusion with MIT License 6 votes vote down vote up
private static Mat calWeight(Mat img, Mat L) {
	Core.divide(L, new Scalar(255.0), L);
	L.convertTo(L, CvType.CV_32F);
	// calculate laplacian contrast weight
	Mat WL = WeightCalculate.LaplacianContrast(L);
	WL.convertTo(WL, L.type());
	// calculate Local contrast weight
	Mat WC = WeightCalculate.LocalContrast(L);
	WC.convertTo(WC, L.type());
	// calculate the saliency weight
	Mat WS = WeightCalculate.Saliency(img);
	WS.convertTo(WS, L.type());
	// calculate the exposedness weight
	Mat WE = WeightCalculate.Exposedness(L);
	WE.convertTo(WE, L.type());
	// sum
	Mat weight = WL.clone();
	Core.add(weight, WC, weight);
	Core.add(weight, WS, weight);
	Core.add(weight, WE, weight);
	return weight;
}
 
Example 8
Source File: Blur.java    From go-bees with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mat process(@NonNull Mat frame) {
    if (frame.empty()) {
        Log.e("Invalid input frame.");
        return null;
    }
    Mat tmp = frame.clone();
    // Apply gaussian blur
    for (int i = 0; i < REPETITIONS; i++) {
        Imgproc.GaussianBlur(tmp, tmp, new Size(KERNEL_SIZE, KERNEL_SIZE), 0);
    }
    return tmp;
}
 
Example 9
Source File: CVProcessor.java    From CVScanner with GNU General Public License v3.0 5 votes vote down vote up
public static Rect detectBorder(Mat original){
    Mat src = original.clone();
    Log.d(TAG, "1 original: " + src.toString());

    Imgproc.GaussianBlur(src, src, new Size(3, 3), 0);
    Log.d(TAG, "2.1 --> Gaussian blur done\n blur: " + src.toString());

    Imgproc.cvtColor(src, src, Imgproc.COLOR_RGBA2GRAY);
    Log.d(TAG, "2.2 --> Grayscaling done\n gray: " + src.toString());

    Mat sobelX = new Mat();
    Mat sobelY = new Mat();

    Imgproc.Sobel(src, sobelX, CvType.CV_32FC1, 2, 0, 5, 1, 0);
    Log.d(TAG, "3.1 --> Sobel done.\n X: " + sobelX.toString());
    Imgproc.Sobel(src, sobelY, CvType.CV_32FC1, 0, 2, 5, 1, 0);
    Log.d(TAG, "3.2 --> Sobel done.\n Y: " + sobelY.toString());

    Mat sum_img = new Mat();
    Core.addWeighted(sobelX, 0.5, sobelY, 0.5, 0.5, sum_img);
    //Core.add(sobelX, sobelY, sum_img);
    Log.d(TAG, "4 --> Addition done. sum: " + sum_img.toString());

    sobelX.release();
    sobelY.release();

    Mat gray = new Mat();
    Core.normalize(sum_img, gray, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC1);
    Log.d(TAG, "5 --> Normalization done. gray: " + gray.toString());
    sum_img.release();

    Mat row_proj = new Mat();
    Mat col_proj = new Mat();
    Core.reduce(gray, row_proj, 1, Core.REDUCE_AVG, CvType.CV_8UC1);
    Log.d(TAG, "6.1 --> Reduce done. row: " + row_proj.toString());

    Core.reduce(gray, col_proj, 0, Core.REDUCE_AVG, CvType.CV_8UC1);
    Log.d(TAG, "6.2 --> Reduce done. col: " + col_proj.toString());
    gray.release();

    Imgproc.Sobel(row_proj, row_proj, CvType.CV_8UC1, 0, 2);
    Log.d(TAG, "7.1 --> Sobel done. row: " + row_proj.toString());

    Imgproc.Sobel(col_proj, col_proj, CvType.CV_8UC1, 2, 0);
    Log.d(TAG, "7.2 --> Sobel done. col: " + col_proj.toString());

    Rect result = new Rect();

    int half_pos = (int) (row_proj.total()/2);
    Mat row_sub = new Mat(row_proj, new Range(0, half_pos), new Range(0, 1));
    Log.d(TAG, "8.1 --> Copy sub matrix done. row: " + row_sub.toString());
    result.y = (int) Core.minMaxLoc(row_sub).maxLoc.y;
    Log.d(TAG, "8.2 --> Minmax done. Y: " + result.y);
    row_sub.release();
    Mat row_sub2 = new Mat(row_proj, new Range(half_pos, (int) row_proj.total()), new Range(0, 1));
    Log.d(TAG, "8.3 --> Copy sub matrix done. row: " + row_sub2.toString());
    result.height = (int) (Core.minMaxLoc(row_sub2).maxLoc.y + half_pos - result.y);
    Log.d(TAG, "8.4 --> Minmax done. Height: " + result.height);
    row_sub2.release();

    half_pos = (int) (col_proj.total()/2);
    Mat col_sub = new Mat(col_proj, new Range(0, 1), new Range(0, half_pos));
    Log.d(TAG, "9.1 --> Copy sub matrix done. col: " + col_sub.toString());
    result.x = (int) Core.minMaxLoc(col_sub).maxLoc.x;
    Log.d(TAG, "9.2 --> Minmax done. X: " + result.x);
    col_sub.release();
    Mat col_sub2 = new Mat(col_proj, new Range(0, 1), new Range(half_pos, (int) col_proj.total()));
    Log.d(TAG, "9.3 --> Copy sub matrix done. col: " + col_sub2.toString());
    result.width = (int) (Core.minMaxLoc(col_sub2).maxLoc.x + half_pos - result.x);
    Log.d(TAG, "9.4 --> Minmax done. Width: " + result.width);
    col_sub2.release();

    row_proj.release();
    col_proj.release();
    src.release();

    return result;
}
 
Example 10
Source File: BackgroundSubtractor.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public Mat createMask(Mat camera) {				
	// copy as we are going to destruct those images maybe
	Mat camBlur= camera.clone();
	Mat backgroundBlur = calib.getBackgroundImage().clone();

	// remove noise
	Imgproc.blur(backgroundBlur, backgroundBlur, new Size(calib.getBlurSize(), calib.getBlurSize()));
	Imgproc.blur(camBlur, camBlur, new Size(calib.getBlurSize(), calib.getBlurSize()));

	// take abs diff and create binary image in all 3 channels
	Mat diff = new Mat();
	Core.absdiff(backgroundBlur, camBlur, diff);
	Imgproc.threshold(diff, diff, calib.getSubtractionThreshold(), 255, Imgproc.THRESH_BINARY);

	// extract color channels and merge them to single bitmask
	Mat r = ColorSpace.getChannel(diff, 2);
	Mat g = ColorSpace.getChannel(diff, 1);
	Mat b = ColorSpace.getChannel(diff, 0);

	Mat mask = r.clone();
	Core.add(mask, g, mask);
	Core.add(mask, b, mask);
	
	// dilate to remove some black gaps within balls
	Imgproc.dilate(mask, mask, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(calib.getMorphSize(), calib.getMorphSize())));

	return mask;
}
 
Example 11
Source File: OpenCVNonMavenExamples.java    From Java-for-Data-Science with MIT License 5 votes vote down vote up
public void smoothImage() {
    // Smoothing, also called blurring, will make the edges soother.
    Mat source = Imgcodecs.imread("cat.jpg");
    Mat destination = source.clone();
    for (int i = 0; i < 25; i++) {
        Mat sourceImage = destination.clone();
        Imgproc.blur(sourceImage, destination, new Size(3.0, 3.0));
    }
    Imgcodecs.imwrite("smoothCat.jpg", destination);
}
 
Example 12
Source File: BlkTransEstimate.java    From OptimizedImageEnhance with MIT License 5 votes vote down vote up
public static double blkEstimateEachChannel(Mat blkIm, double airlight, double lambda, double fTrans) {
	double Trans = 0.0;
	double nTrans = Math.floor(1.0 / fTrans * 128);
	double fMinCost = Double.MAX_VALUE;
	int numberOfPixels = blkIm.rows() * blkIm.cols() * blkIm.channels();
	int nCounter = 0;
	while (nCounter < (int) (1 - fTrans) * 10) {
		// initial dehazing process to calculate the loss information
		Mat channel = blkIm.clone();
		channel = preDehaze(channel, airlight, nTrans);
		// find the pixels with over-255 value and below-0 value, and
		// calculate the sum of information loss
		double nSumOfLoss = 0.0;
		for (int i = 0; i < channel.rows(); i++) {
			for (int j = 0; j < channel.cols(); j++) {
				if (channel.get(i, j)[0] > 255.0) nSumOfLoss += (channel.get(i, j)[0] - 255.0) * (channel.get(i, j)[0] - 255.0);
				else if (channel.get(i, j)[0] < 0.0) nSumOfLoss += channel.get(i, j)[0] * channel.get(i, j)[0];
			}
		}
		// calculate the value of sum of square out
		double nSumOfSquareOuts = Core.sumElems(channel.mul(channel)).val[0];
		// calculate the value of sum of out
		double nSumOfOuts = Core.sumElems(channel).val[0];
		// calculate the mean value of the block image
		double fMean = nSumOfOuts / numberOfPixels;
		// calculate the cost function
		double fCost = lambda * nSumOfLoss / numberOfPixels - (nSumOfSquareOuts / numberOfPixels - fMean * fMean);
		// find the minimum cost and the related transmission
		if (nCounter == 0 || fMinCost > fCost) {
			fMinCost = fCost;
			Trans = fTrans;
		}
		fTrans = fTrans + 0.1;
		nTrans = 1.0 / fTrans * 128;
		nCounter = nCounter + 1;
	}
	return Trans;
}
 
Example 13
Source File: RemoveBackScatter.java    From OptimizedImageEnhance with MIT License 5 votes vote down vote up
private static Mat dehazeProcess(Mat img, Mat trans, double[] airlight) {
	Mat balancedImg = Filters.SimplestColorBalance(img, 5);
	Mat bCnl = new Mat();
	Core.extractChannel(balancedImg, bCnl, 0);
	Mat gCnl = new Mat();
	Core.extractChannel(balancedImg, gCnl, 1);
	Mat rCnl = new Mat();
	Core.extractChannel(balancedImg, rCnl, 2);
	// get mean value
	double bMean = Core.mean(bCnl).val[0];
	double gMean = Core.mean(gCnl).val[0];
	double rMean = Core.mean(rCnl).val[0];
	// get transmission map for each channel
	Mat Tb = trans.clone();
	Core.multiply(Tb, new Scalar(Math.max(bMean, Math.max(gMean, rMean)) / bMean * 0.8), Tb);
	Mat Tg = trans.clone();
	Core.multiply(Tg, new Scalar(Math.max(bMean, Math.max(gMean, rMean)) / gMean * 0.9), Tg);
	Mat Tr = trans.clone();
	Core.multiply(Tr, new Scalar(Math.max(bMean, Math.max(gMean, rMean)) / rMean * 0.8), Tr);
	// dehaze by formula
	// blue channel
	Mat bChannel = new Mat();
	Core.subtract(bCnl, new Scalar(airlight[0]), bChannel);
	Core.divide(bChannel, Tb, bChannel);
	Core.add(bChannel, new Scalar(airlight[0]), bChannel);
	// green channel
	Mat gChannel = new Mat();
	Core.subtract(gCnl, new Scalar(airlight[1]), gChannel);
	Core.divide(gChannel, Tg, gChannel);
	Core.add(gChannel, new Scalar(airlight[1]), gChannel);
	// red channel
	Mat rChannel = new Mat();
	Core.subtract(rCnl, new Scalar(airlight[2]), rChannel);
	Core.divide(rChannel, Tr, rChannel);
	Core.add(rChannel, new Scalar(airlight[2]), rChannel);
	Mat dehazed = new Mat();
	Core.merge(new ArrayList<>(Arrays.asList(bChannel, gChannel, rChannel)), dehazed);
	return dehazed;
}
 
Example 14
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 15
Source File: CVProcessor.java    From CVScanner with GNU General Public License v3.0 4 votes vote down vote up
public static List<MatOfPoint> findContours(Mat src){
    Mat img = src.clone();

    //find contours
    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);
    img.release();

    Imgproc.medianBlur(resizedImg, resizedImg, 7);

    Mat cannedImg = new Mat(newSize, CvType.CV_8UC1);
    Imgproc.Canny(resizedImg, cannedImg, 70, 200, 3, true);
    resizedImg.release();

    Imgproc.threshold(cannedImg, cannedImg, 70, 255, Imgproc.THRESH_OTSU);

    Mat dilatedImg = new Mat(newSize, CvType.CV_8UC1);
    Mat morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3));
    Imgproc.dilate(cannedImg, dilatedImg, morph, new Point(-1, -1), 2, 1, new Scalar(1));
    cannedImg.release();
    morph.release();

    ArrayList<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(dilatedImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    hierarchy.release();
    dilatedImg.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 16
Source File: EnhanceFunc.java    From ImageEnhanceViaFusion with MIT License 4 votes vote down vote up
public static void main(String[] args) {
	String imgPath = "images/5.jpg";
	Mat image = Imgcodecs.imread(imgPath, Imgcodecs.CV_LOAD_IMAGE_COLOR);
	new ImShow("original").showImage(image);
	// color balance
	Mat img1 = ColorBalance.SimplestColorBalance(image, 5);
	img1.convertTo(img1, CvType.CV_8UC1);
	// Perform sRGB to CIE Lab color space conversion
	Mat LabIm1 = new Mat();
	Imgproc.cvtColor(img1, LabIm1, Imgproc.COLOR_BGR2Lab);
	Mat L1 = new Mat();
	Core.extractChannel(LabIm1, L1, 0);
	// apply CLAHE
	Mat[] result = applyCLAHE(LabIm1, L1);
	Mat img2 = result[0];
	Mat L2 = result[1];
	// calculate normalized weight
	Mat w1 = calWeight(img1, L1);
	Mat w2 = calWeight(img2, L2);
	Mat sumW = new Mat();
	Core.add(w1, w2, sumW);
	Core.divide(w1, sumW, w1);
	Core.divide(w2, sumW, w2);
	// construct the gaussian pyramid for weight
	int level = 5;
	Mat[] weight1 = Pyramid.GaussianPyramid(w1, level);
	Mat[] weight2 = Pyramid.GaussianPyramid(w2, level);
	// construct the laplacian pyramid for input image channel
	img1.convertTo(img1, CvType.CV_32F);
	img2.convertTo(img2, CvType.CV_32F);
	List<Mat> bgr = new ArrayList<Mat>();
	Core.split(img1, bgr);
	Mat[] bCnl1 = Pyramid.LaplacianPyramid(bgr.get(0), level);
	Mat[] gCnl1 = Pyramid.LaplacianPyramid(bgr.get(1), level);
	Mat[] rCnl1 = Pyramid.LaplacianPyramid(bgr.get(2), level);
	bgr.clear();
	Core.split(img2, bgr);
	Mat[] bCnl2 = Pyramid.LaplacianPyramid(bgr.get(0), level);
	Mat[] gCnl2 = Pyramid.LaplacianPyramid(bgr.get(1), level);
	Mat[] rCnl2 = Pyramid.LaplacianPyramid(bgr.get(2), level);
	// fusion process
	Mat[] bCnl = new Mat[level];
	Mat[] gCnl = new Mat[level];
	Mat[] rCnl = new Mat[level];
	for (int i = 0; i < level; i++) {
		Mat cn = new Mat();
		Core.add(bCnl1[i].mul(weight1[i]), bCnl2[i].mul(weight2[i]), cn);
		bCnl[i] = cn.clone();
		Core.add(gCnl1[i].mul(weight1[i]), gCnl2[i].mul(weight2[i]), cn);
		gCnl[i] = cn.clone();
		Core.add(rCnl1[i].mul(weight1[i]), rCnl2[i].mul(weight2[i]), cn);
		rCnl[i] = cn.clone();
	}
	// reconstruct & output
	Mat bChannel = Pyramid.PyramidReconstruct(bCnl);
	Mat gChannel = Pyramid.PyramidReconstruct(gCnl);
	Mat rChannel = Pyramid.PyramidReconstruct(rCnl);
	Mat fusion = new Mat();
	Core.merge(new ArrayList<Mat>(Arrays.asList(bChannel, gChannel, rChannel)), fusion);
	fusion.convertTo(fusion, CvType.CV_8UC1);
	new ImShow("fusion").showImage(fusion);
}
 
Example 17
Source File: DarkChannelPriorDehaze.java    From OptimizedImageEnhance with MIT License 4 votes vote down vote up
public static Mat enhance(Mat image, double krnlRatio, double minAtmosLight, double eps) {
	image.convertTo(image, CvType.CV_32F);
	// extract each color channel
	List<Mat> rgb = new ArrayList<>();
	Core.split(image, rgb);
	Mat rChannel = rgb.get(0);
	Mat gChannel = rgb.get(1);
	Mat bChannel = rgb.get(2);
	int rows = rChannel.rows();
	int cols = rChannel.cols();
	// derive the dark channel from original image
	Mat dc = rChannel.clone();
	for (int i = 0; i < image.rows(); i++) {
		for (int j = 0; j < image.cols(); j++) {
			double min = Math.min(rChannel.get(i, j)[0], Math.min(gChannel.get(i, j)[0], bChannel.get(i, j)[0]));
			dc.put(i, j, min);
		}
	}
	// minimum filter
	int krnlSz = Double.valueOf(Math.max(Math.max(rows * krnlRatio, cols * krnlRatio), 3.0)).intValue();
	Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(krnlSz, krnlSz), new Point(-1, -1));
	Imgproc.erode(dc, dc, kernel);
	// get coarse transmission map
	Mat t = dc.clone();
	Core.subtract(t, new Scalar(255.0), t);
	Core.multiply(t, new Scalar(-1.0), t);
	Core.divide(t, new Scalar(255.0), t);
	// obtain gray scale image
	Mat gray = new Mat();
	Imgproc.cvtColor(image, gray, Imgproc.COLOR_RGB2GRAY);
	Core.divide(gray, new Scalar(255.0), gray);
	// refine transmission map
	int r = krnlSz * 4;
	t = Filters.GuidedImageFilter(gray, t, r, eps);
	// get minimum atmospheric light
	minAtmosLight = Math.min(minAtmosLight, Core.minMaxLoc(dc).maxVal);
	// dehaze each color channel
	rChannel = dehaze(rChannel, t, minAtmosLight);
	gChannel = dehaze(gChannel, t, minAtmosLight);
	bChannel = dehaze(bChannel, t, minAtmosLight);
	// merge three color channels to a image
	Mat outval = new Mat();
	Core.merge(new ArrayList<>(Arrays.asList(rChannel, gChannel, bChannel)), outval);
	outval.convertTo(outval, CvType.CV_8UC1);
	return outval;
}
 
Example 18
Source File: PrimitiveDetection.java    From FTCVision with MIT License 4 votes vote down vote up
/**
 * Locate rectangles in an image
 *
 * @param grayImage Grayscale image
 * @return Rectangle locations
 */
public RectangleLocationResult locateRectangles(Mat grayImage) {
    Mat gray = grayImage.clone();

    //Filter out some noise by halving then doubling size
    Filter.downsample(gray, 2);
    Filter.upsample(gray, 2);

    //Mat is short for Matrix, and here is used to store an image.
    //it is n-dimensional, but as an image, is two-dimensional
    Mat cacheHierarchy = new Mat();
    Mat grayTemp = new Mat();
    List<Rectangle> rectangles = new ArrayList<>();
    List<Contour> contours = new ArrayList<>();

    //This finds the edges using a Canny Edge Detector
    //It is sent the grayscale Image, a temp Mat, the lower detection threshold for an edge,
    //the higher detection threshold, the Aperture (blurring) of the image - higher is better
    //for long, smooth edges, and whether a more accurate version (but time-expensive) version
    //should be used (true = more accurate)
    //Note: the edges are stored in "grayTemp", which is an image where everything
    //is black except for gray-scale lines delineating the edges.
    Imgproc.Canny(gray, grayTemp, 0, THRESHOLD_CANNY, APERTURE_CANNY, true);
    //make the white lines twice as big, while leaving the image size constant
    Filter.dilate(gray, 2);

    List<MatOfPoint> contoursTemp = new ArrayList<>();
    //Find contours - the parameters here are very important to compression and retention
    //grayTemp is the image from which the contours are found,
    //contoursTemp is where the resultant contours are stored (note: color is not retained),
    //cacheHierarchy is the parent-child relationship between the contours (e.g. a contour
    //inside of another is its child),
    //Imgproc.CV_RETR_LIST disables the hierarchical relationships being returned,
    //Imgproc.CHAIN_APPROX_SIMPLE means that the contour is compressed from a massive chain of
    //paired coordinates to just the endpoints of each segment (e.g. an up-right rectangular
    //contour is encoded with 4 points.)
    Imgproc.findContours(grayTemp, contoursTemp, cacheHierarchy, Imgproc.CV_RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    //MatOfPoint2f means that is a MatofPoint (Matrix of Points) represented by floats instead of ints
    MatOfPoint2f approx = new MatOfPoint2f();
    //For each contour, test whether the contour is a rectangle
    //List<Contour> contours = new ArrayList<>()
    for (MatOfPoint co : contoursTemp) {
        //converting the MatOfPoint to MatOfPoint2f
        MatOfPoint2f matOfPoint2f = new MatOfPoint2f(co.toArray());
        //converting the matrix to a Contour
        Contour c = new Contour(co);

        //Attempt to fit the contour to the best polygon
        //input: matOfPoint2f, which is the contour found earlier
        //output: approx, which is the MatOfPoint2f that holds the new polygon that has less vertices
        //basically, it smooths out the edges using the third parameter as its approximation accuracy
        //final parameter determines whether the new approximation must be closed (true=closed)
        Imgproc.approxPolyDP(matOfPoint2f, approx,
                c.arcLength(true) * EPLISON_APPROX_TOLERANCE_FACTOR, true);

        //converting the MatOfPoint2f to a contour
        Contour approxContour = new Contour(approx);

        //Make sure the contour is big enough, CLOSED (convex), and has exactly 4 points
        if (approx.toArray().length == 4 &&
                Math.abs(approxContour.area()) > 1000 &&
                approxContour.isClosed()) {

            //TODO contours and rectangles array may not match up, but why would they?
            contours.add(approxContour);

            //Check each angle to be approximately 90 degrees
            //Done by comparing the three points constituting the angle of each corner
            double maxCosine = 0;
            for (int j = 2; j < 5; j++) {
                double cosine = Math.abs(MathUtil.angle(approx.toArray()[j % 4],
                        approx.toArray()[j - 2], approx.toArray()[j - 1]));
                maxCosine = Math.max(maxCosine, cosine);
            }

            if (maxCosine < MAX_COSINE_VALUE) {
                //Convert the points to a rectangle instance
                rectangles.add(new Rectangle(approx.toArray()));
            }
        }
    }

    return new RectangleLocationResult(contours, rectangles);
}
 
Example 19
Source File: BinaryUtils.java    From super-cloudops with Apache License 2.0 2 votes vote down vote up
/**
 * opencv自带的二值化
 * 
 * @param src
 * @return
 */
public static Mat binaryNative(Mat src) {
	Mat dst = src.clone();
	Imgproc.adaptiveThreshold(src, dst, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 25, 10);
	return dst;
}
 
Example 20
Source File: GeneralUtils.java    From super-cloudops with Apache License 2.0 2 votes vote down vote up
/**
 * canny算法,边缘检测
 *
 * @param src
 * @return
 */
public static Mat canny(Mat src) {
	Mat mat = src.clone();
	Imgproc.Canny(src, mat, 60, 200);
	return mat;
}