Mat是OpenCV中用来存储图像信息的内存对象,当通过Imgcodecs.imread()方法从文件读入一个图像文件时,imread方法就会返回Mat对象实例,或者通过Utils.bitmapToMat()方法由Bitmap对象转换而来。
Mat src = Imgcodecs.imread(fileUri.getPath());
指定加载方法
Mat src=Imgcodecs.imread(fileUri.getPath(), Imgcodecs.IMREAD_COLOR);
PS:
Imgcodecs.IMREAD_COLOR=1,彩色图像
Imgcodecs.IMREAD_GRAYSCALE=1,灰度图像
Imgcodecs.IMREAD_UNCHANGED=1,不改变加载图像类型,可能包含透明通道
int width = src.cols();宽
int height = src.rows();高
int dims = src.dims();维度
int channels = src.channels();通道数
int depth = src.depth();深度
int type = src.type();类型信息
(1)creat方法创建
Mat m1 = new Mat();
m1.create(new Size(3, 3), CvType.CV_8UC3);
Mat m2 = new Mat();
m2.create(3, 3, CvType.CV_8UC3);
(2)ones、eye、zeros方法创建
Mat m3 = Mat.eye(3, 3,CvType.CV_8UC3);
Mat m4 = Mat.eye(new Size(3, 3),CvType.CV_8UC3);
Mat m5 = Mat.zeros(new Size(3, 3), CvType.CV_8UC3);
Mat m6 = Mat.ones(new Size(3, 3), CvType.CV_8UC3);
(3)setTo方法创建
Mat m7 = new Mat(3, 3, CvType.CV_8UC3);
m7.setTo(new Scalar(255, 255, 255));
(4)copyTo方法创建
Mat m8 = new Mat(500, 500, CvType.CV_8UC3);
m8.setTo(new Scalar(127, 127, 127));
Mat result = new Mat();
m8.copyTo(result);
Mat image = new Mat(500, 500, CvType.CV_8UC3);
image.setTo(new Scalar(127, 127, 127));
ImageSelectUtils.saveImage(image);
Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.lena);
PS:当前Android支持的Bitmap像素存储类型为:
Bitmap.Config.ALPHA_8;
Bitmap.Config.ARGB_4444;
Bitmap.Config.RGB_565;
Bitmap.Config.ARGB_8888;
int a=0, r=0, g=0, b=0;
for(int row=0; row<height; row++) {
for(int col=0; col<width; col++) {
// 读取像素
int pixel = bm.getPixel(col, row);
a = Color.alpha(pixel);
r = Color.red(pixel);
g = Color.green(pixel);
b = Color.blue(pixel);
// 修改像素
r = 255 - r;
g = 255 - g;
b = 255 - b;
// 保存到Bitmap中
bm.setPixel(col, row, Color.argb(a, r, g, b));
}
}
int[] pixels = new int[width*height];
bm.getPixels(pixels, 0, width, 0, 0, width, height);
int a=0, r=0, g=0, b=0;
int index = 0;
for(int row=0; row<height; row++) {
for(int col=0; col<width; col++) {
// 读取像素
index = width*row + col;
a=(pixels[index]>>24)&0xff;
r=(pixels[index]>>16)&0xff;
g=(pixels[index]>>8)&0xff;
b=pixels[index]&0xff;
// 修改像素
r = 255 - r;
g = 255 - g;
b = 255 - b;
// 保存到Bitmap中
pixels[index] = (a << 24) | (r << 16) | (g << 8) | b;
}
}