Mat作爲圖像的邏輯結構,是二維多通道的。如何訪問圖像的元素,以及像素的各個通道,是本文的重點。
package com.linghushaoxia.javacv.chapter02;
import static org.bytedeco.javacpp.opencv_imgcodecs.IMREAD_COLOR;
import java.util.Random;
import org.bytedeco.javacpp.indexer.UByteIndexer;
import org.bytedeco.javacpp.opencv_core.Mat;
import com.linghushaoxia.image.util.JavaCVUtil;
/**功能說明:對圖片添加噪點(加鹽處理)
* @author:linghushaoxia
* @time:2016年4月19日下午8:39:09
* @version:1.0
* 爲中國孱弱的技術,
* 撐起一片自立自強的天空
*/
public class ImageSalt {
public static void main(String[] args) {
//圖片路徑
String filePath = "data/javacv/tower.JPG";
// 以彩色模式讀取圖像
Mat image = JavaCVUtil.imRead(filePath, IMREAD_COLOR);
//原始圖像
JavaCVUtil.imShow(image,"原始圖片");
//對圖像加鹽
Mat dest = salt(image, 2000);
// 顯示圖像
JavaCVUtil.imShow(dest, "加鹽處理");
}
/**
*
* 功能說明:對圖片加鹽,添加噪點
* @param image
* 原始圖片
* @param n
* 噪點數量
* @return Mat
* @time:2016年4月19日下午8:40:27
* @author:linghushaoxia
* @exception:
*
*/
public static Mat salt(Mat image, int n) {
// 隨機數生成對象
Random random = new Random();
/**
* 無符號字節索引,訪問Mat結構的元素
* 訪問Mat高效便捷
*/
UByteIndexer indexer = image.createIndexer();
//圖像通道
int nbChannels = image.channels();
//加鹽數量
for (int i = 0; i < n; i++) {
/**
* 獲取隨機行、列
* 噪點隨機分佈
*/
int row = random.nextInt(image.rows());
int col = random.nextInt(image.cols());
//處理全部通道數據,均進行加鹽,設置爲最大值255
for (int channel = 0; channel < nbChannels; channel++) {
indexer.put(row, col, channel, 255);
}
}
return image;
}
}
/**
* 現實就是實現理想的過程。
*
*/
原始圖片
加鹽處理