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

The following examples show how to use org.opencv.core.Mat#channels() . 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: GeneralUtils.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 作用:翻转图像像素
 *
 * @param src
 *            Mat矩阵图像
 * @return
 */
public static Mat turnPixel(Mat src) {
	if (src.channels() != 1) {
		throw new RuntimeException("不是单通道图,需要先灰度话!!!");
	}
	int j, i, value;
	int width = getImgWidth(src), height = getImgHeight(src);
	for (j = 0; j < height; j++) {
		for (i = 0; i < width; i++) {
			value = getPixel(src, j, i);
			if (value == 0) {
				setPixel(src, j, i, WHITE);
			} else {
				setPixel(src, j, i, BLACK);
			}
		}
	}
	return src;
}
 
Example 2
Source File: Webcam.java    From ResCan with GNU General Public License v2.0 6 votes vote down vote up
public static Image toBufferedImage(Mat m) {
	int type = BufferedImage.TYPE_BYTE_GRAY;
	if (m.channels() > 1) {
		Mat m2 = new Mat();
		m2 = m;
		// Imgproc.cvtColor(m,m2,Imgproc.COLOR_BGR2RGB);
		type = BufferedImage.TYPE_3BYTE_BGR;
		m = m2;
	}
	byte[] b = new byte[m.channels() * m.cols() * m.rows()];
	m.get(0, 0, b); // get all the pixels
	BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
	image.getRaster().setDataElements(0, 0, m.cols(), m.rows(), b);
	return image;

}
 
Example 3
Source File: FaceRecognitionAppActivity.java    From FaceRecognitionApp with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
public void SaveImage(Mat mat) {
    Mat mIntermediateMat = new Mat();

    if (mat.channels() == 1) // Grayscale image
        Imgproc.cvtColor(mat, mIntermediateMat, Imgproc.COLOR_GRAY2BGR);
    else
        Imgproc.cvtColor(mat, mIntermediateMat, Imgproc.COLOR_RGBA2BGR);

    File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), TAG); // Save pictures in Pictures directory
    path.mkdir(); // Create directory if needed
    String fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US).format(new Date()) + ".png";
    File file = new File(path, fileName);

    boolean bool = Imgcodecs.imwrite(file.toString(), mIntermediateMat);

    if (bool)
        Log.i(TAG, "SUCCESS writing image to external storage");
    else
        Log.e(TAG, "Failed writing image to external storage");
}
 
Example 4
Source File: GrayUtils.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 全局自适应阀值灰度化降噪
 * 
 * @param src
 * @return
 */
public static Mat grayColByAdapThreshold(Mat src) {
	if (src.channels() != 1) {
		src = grayNative(src);
	}
	int i, j;
	int width = GeneralUtils.getImgWidth(src), height = GeneralUtils.getImgHeight(src);
	int value;

	int threshold = getAdapThreshold(src);
	for (j = 0; j < height; j++) {
		for (i = 0; i < width; i++) {
			value = GeneralUtils.getPixel(src, j, i);
			if (value > threshold) {
				GeneralUtils.setPixel(src, j, i, GeneralUtils.getWHITE());

			}
		}
	}

	return src;
}
 
Example 5
Source File: Util.java    From OpenTLDAndroid with Apache License 2.0 5 votes vote down vote up
static int[] getIntArray(final Mat mat){
	if(CvType.CV_32SC1 != mat.type()) throw new IllegalArgumentException("Expected type is CV_32SC1, we found: " + CvType.typeToString(mat.type()));
	
	final int size = (int) (mat.total() * mat.channels());
	if(_intBuff.length != size){
		_intBuff = new int[size];
	}
	mat.get(0, 0, _intBuff); // 0 for row and col means the WHOLE Matrix
	return _intBuff;
}
 
Example 6
Source File: ImShow.java    From OptimizedImageEnhance with MIT License 5 votes vote down vote up
public BufferedImage toBufferedImage(Mat m) {
	int type = BufferedImage.TYPE_BYTE_GRAY;
	if (m.channels() > 1) type = BufferedImage.TYPE_3BYTE_BGR;
	int bufferSize = m.channels() * m.cols() * m.rows();
	byte[] b = new byte[bufferSize];
	m.get(0, 0, b); // get all the pixels
	BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
	final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
	System.arraycopy(b, 0, targetPixels, 0, b.length);
	return image;
}
 
Example 7
Source File: Filters.java    From OptimizedImageEnhance with MIT License 5 votes vote down vote up
/**
 * Simplest Color Balance. Performs color balancing via histogram
 * normalization.
 *
 * @param img input color or gray scale image
 * @param percent controls the percentage of pixels to clip to white and black. (normally, choose 1~10)
 * @return Balanced image in CvType.CV_32F
 */
public static Mat SimplestColorBalance(Mat img, int percent) {
	if (percent <= 0)
		percent = 5;
	img.convertTo(img, CvType.CV_32F);
	List<Mat> channels = new ArrayList<>();
	int rows = img.rows(); // number of rows of image
	int cols = img.cols(); // number of columns of image
	int chnls = img.channels(); //  number of channels of image
	double halfPercent = percent / 200.0;
	if (chnls == 3) Core.split(img, channels);
	else channels.add(img);
	List<Mat> results = new ArrayList<>();
	for (int i = 0; i < chnls; i++) {
		// find the low and high precentile values (based on the input percentile)
		Mat flat = new Mat();
		channels.get(i).reshape(1, 1).copyTo(flat);
		Core.sort(flat, flat, Core.SORT_ASCENDING);
		double lowVal = flat.get(0, (int) Math.floor(flat.cols() * halfPercent))[0];
		double topVal = flat.get(0, (int) Math.ceil(flat.cols() * (1.0 - halfPercent)))[0];
		// saturate below the low percentile and above the high percentile
		Mat channel = channels.get(i);
		for (int m = 0; m < rows; m++) {
			for (int n = 0; n < cols; n++) {
				if (channel.get(m, n)[0] < lowVal) channel.put(m, n, lowVal);
				if (channel.get(m, n)[0] > topVal) channel.put(m, n, topVal);
			}
		}
		Core.normalize(channel, channel, 0.0, 255.0 / 2, Core.NORM_MINMAX);
		channel.convertTo(channel, CvType.CV_32F);
		results.add(channel);
	}
	Mat outval = new Mat();
	Core.merge(results, outval);
	return outval;
}
 
Example 8
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 9
Source File: ImgprocessUtils.java    From classchecks with Apache License 2.0 5 votes vote down vote up
/**
 * 将源图像转换为灰度图
 * @param srcImg
 * @return
 */
public static Mat covertImage2Gray(Mat srcImg) {
	Mat gray = new Mat(); // 存储灰度图
	if (srcImg.channels() == 3) {
		Imgproc.cvtColor(srcImg, gray, Imgproc.COLOR_BGR2GRAY);
	} else if (srcImg.channels() == 4) {
		Imgproc.cvtColor(srcImg, gray, Imgproc.COLOR_BGRA2GRAY);
	} else {
		gray = srcImg;
	}
	return gray;
}
 
Example 10
Source File: GrayUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * 根据灰度化后的图像每一列的像素值的第k大值作为阀值,把大于阀值的像素都改为255
 * 
 * @param src
 * @param k
 * @param data
 * @return
 */
public static Mat grayColByKLargest(Mat src, int k, List<List<Double>> data) {
	if (k == 0) {
		throw new RuntimeException("k不能为0");
	}
	if (src.channels() != 1) {
		src = grayNative(src);
	}
	for (int j = 0; j < data.size(); j++) {
		List<Double> list = data.get(j);
		Object[] doubles = list.toArray();
		Double[] doubles1 = new Double[doubles.length];
		for (int i = 0; i < doubles.length; i++) {
			doubles1[i] = (Double) doubles[i];
		}
		double d = MathUtils.findKthLargest(doubles1, list.size() / k);

		// 随机的更新像素值
		int count = 3 * doubles.length / 4;
		int time = 0;
		while (count > 0) {
			int index = new Random().nextInt(list.size());
			if (list.get(index) >= d) {
				src.put(index, j, 255);
				count--;
			}
			time++;
			// 避免程序进入死循环
			if (time == list.size() / 2) {
				break;
			}
		}
	}
	return src;
}
 
Example 11
Source File: GrayUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * 根据灰度化后的图像每一列的像素值的第k大值作为阀值,把大于阀值的像素都改为255
 * 
 * @param src
 * @param k
 *            分母
 * @return
 */
public static Mat grayColByKLargest(Mat src, int k) {
	if (k == 0) {
		throw new RuntimeException("k不能为0");
	}
	if (src.channels() != 1) {
		src = grayNative(src);
	}
	List<List<Double>> data = MathUtils.MatPixelToList(src);
	return grayColByKLargest(src, k, data);
}
 
Example 12
Source File: GrayUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * k值灰度化减噪 根据灰度化后的图像每一列的像素值的第k大值作为阀值,把大于阀值的像素都改为255 默认选取第1/3大的值作为阀值
 * 
 * @param src
 * @return
 */
public static Mat grayColByKLargest(Mat src) {
	if (src.channels() != 1) {
		src = grayNative(src);
	}
	List<List<Double>> data = MathUtils.MatPixelToList(src);
	return grayColByKLargest(src, 3, data);
}
 
Example 13
Source File: GrayUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * 根据灰度化后的图像每一列的像素值的平均值作为阀值,把大于阀值的像素都改为255
 * 
 * @param data
 *            List<Double>中存储图像灰度化后的每一列的像素值
 * @return
 */
public static Mat grayColByMidle(Mat src, List<List<Double>> data) {
	if (src.channels() != 1) {
		src = grayNative(src);
	}
	for (int j = 0; j < data.size(); j++) {
		List<Double> list = data.get(j);

		int avg = (int) ((MathUtils.getSumInList(list) / list.size()) * 0.95);

		// 随机的更新像素值
		int count = 3 * list.size() / 4;
		int time = 0;
		while (count > 0) {
			int index = new Random().nextInt(list.size());
			if (list.get(index) >= avg) {
				src.put(index, j, 255);
				count--;
			}
			time++;
			// 避免程序进入死循环
			if (time == list.size() / 2) {
				break;
			}
		}
	}
	return src;
}
 
Example 14
Source File: ColorSpace.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Mat getChannel(Mat img, int channelIdx) {
	List<Mat> channels = new ArrayList<Mat>();
	for(int i = 0; i < img.channels(); i++) {
		Mat channel = new Mat();
		channels.add(channel);
	}
	Core.split(img, channels);
	return channels.get(channelIdx);
}
 
Example 15
Source File: Util.java    From OpenTLDAndroid with Apache License 2.0 5 votes vote down vote up
static double[] getDoubleArray(final Mat mat){
	if(CvType.CV_64F != mat.type()) throw new IllegalArgumentException("Expected type is CV_64F, we found: " + CvType.typeToString(mat.type()));
	
	final int size = (int) (mat.total() * mat.channels());
	if(_doubleBuff.length != size){
		_doubleBuff = new double[size];
	}
	mat.get(0, 0, _doubleBuff); // 0 for row and col means the WHOLE Matrix
	return _doubleBuff;
}
 
Example 16
Source File: BinaryUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * 图像二值化 阀值自适应确定
 *
 * @param src
 *            Mat矩阵图像
 * @return
 */
public static Mat binaryzation(Mat src) {
	if (src.channels() != 1) {
		throw new RuntimeException("不是单通道图,需要先灰度话!!!");
	}
	int threshold = getAdapThreshold(src);
	return binaryzation(src, threshold);
}
 
Example 17
Source File: BlkTransEstimate.java    From OptimizedImageEnhance with MIT License 4 votes vote down vote up
public static double blkEstimate(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();
	double nCounter = 0.0;
	List<Mat> bgr = new ArrayList<>();
	Core.split(blkIm, bgr);
	while (nCounter < (1.0 - fTrans) * 10) {
		// initial dehazing process to calculate the loss information
		Mat bChannel = bgr.get(0).clone();
		bChannel = preDehaze(bChannel, airlight[0], nTrans);
		Mat gChannel = bgr.get(1).clone();
		gChannel = preDehaze(gChannel, airlight[1], nTrans);
		Mat rChannel = bgr.get(2).clone();
		rChannel = preDehaze(rChannel, airlight[2], 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 < bChannel.rows(); i++) {
			for (int j = 0; j < bChannel.cols(); j++) {
				if (bChannel.get(i, j)[0] > 255.0) nSumOfLoss += (bChannel.get(i, j)[0] - 255.0) * (bChannel.get(i, j)[0] - 255.0);
				else if (bChannel.get(i, j)[0] < 0.0) nSumOfLoss += bChannel.get(i, j)[0] * bChannel.get(i, j)[0];
				if (gChannel.get(i, j)[0] > 255.0) nSumOfLoss += (gChannel.get(i, j)[0] - 255.0) * (gChannel.get(i, j)[0] - 255.0);
				else if (gChannel.get(i, j)[0] < 0.0) nSumOfLoss += gChannel.get(i, j)[0] * gChannel.get(i, j)[0];
				if (rChannel.get(i, j)[0] > 255.0) nSumOfLoss += (rChannel.get(i, j)[0] - 255.0) * (rChannel.get(i, j)[0] - 255.0);
				else if (rChannel.get(i, j)[0] < 0.0) nSumOfLoss += rChannel.get(i, j)[0] * rChannel.get(i, j)[0];
			}
		}
		// calculate the value of sum of square out
		double nSumOfSquareOuts = Core.sumElems(bChannel.mul(bChannel)).val[0] + Core.sumElems(gChannel.mul(gChannel)).val[0] + Core.sumElems(rChannel.mul(rChannel)).val[0];
		// calculate the value of sum of out
		double nSumOfOuts = Core.sumElems(bChannel).val[0] + Core.sumElems(gChannel).val[0] + Core.sumElems(rChannel).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.0;
		nCounter = nCounter + 1;
	}
	return Trans;
}
 
Example 18
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 19
Source File: ColorBalance.java    From ImageEnhanceViaFusion with MIT License 4 votes vote down vote up
/**
 * Simplest Color Balance. Performs color balancing via histogram
 * normalization.
 *
 * @param img
 *            input color or gray scale image
 * @param percent
 *            controls the percentage of pixels to clip to white and black.
 *            (normally, choose 1~10)
 * @return Balanced image in CvType.CV_32F
 */
public static Mat SimplestColorBalance(Mat img, int percent) {
	if (percent <= 0)
		percent = 5;
	img.convertTo(img, CvType.CV_32F);
	List<Mat> channels = new ArrayList<Mat>();
	int rows = img.rows(); // number of rows of image
	int cols = img.cols(); // number of columns of image
	int chnls = img.channels(); //  number of channels of image
	double halfPercent = percent / 200.0;
	if (chnls == 3) {
		Core.split(img, channels);
	} else {
		channels.add(img);
	}
	List<Mat> results = new ArrayList<Mat>();
	for (int i = 0; i < chnls; i++) {
		// find the low and high precentile values (based on the input percentile)
		Mat flat = new Mat();
		channels.get(i).reshape(1, 1).copyTo(flat);
		Core.sort(flat, flat, Core.SORT_ASCENDING);
		double lowVal = flat.get(0, (int) Math.floor(flat.cols() * halfPercent))[0];
		double topVal = flat.get(0, (int) Math.ceil(flat.cols() * (1.0 - halfPercent)))[0];
		// saturate below the low percentile and above the high percentile
		Mat channel = channels.get(i);
		for (int m = 0; m < rows; m++) {
			for (int n = 0; n < cols; n++) {
				if (channel.get(m, n)[0] < lowVal)
					channel.put(m, n, lowVal);
				if (channel.get(m, n)[0] > topVal)
					channel.put(m, n, topVal);
			}
		}
		Core.normalize(channel, channel, 0, 255, Core.NORM_MINMAX);
		channel.convertTo(channel, CvType.CV_32F);
		results.add(channel);
	}
	Mat outval = new Mat();
	Core.merge(results, outval);
	return outval;
}
 
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;

}