前面我们说到了用Mat类进行行列式的计算,可能在OPenCv中不算太实用,那么今天我们介绍一个比较使用的,图片中的像素点
我们知道OpenCv当我们read一个图片的时候,返回的结果是一个Mat
一. Mat的结构
Mat的结构是怎样的,我们来看一下:
1. dataAddr 在C++中有指针的概念,指针是以一个变量,指向内存中存储空间(可能是联系的,也可能不是连续的),我们使用opencv,java在本质上还是使用的C++
2,nativeObj 相当于是本地的一个对象
3.isSubmat 是否为子矩阵
4.isCont 是否联系存储
5.512*512*CV_UC3 标识size和type
二.如何画一条直线,如图所示:
直接看代码:
public static void main(String[] args) throws IOException {
try {
ResourceBundle bundle = ResourceBundle.getBundle("opencv");
String opencvDllName = bundle.getString("opencv.dllpath");
System.load(opencvDllName);
} catch (Exception e) {
e.printStackTrace();
}
Mat truth = new Mat(500, 500, CvType.CV_8UC3);
byte [] line=new byte[truth.channels()*truth.width()];
for(int i=0;i<line.length;i++) {
line[i]=125;
}
truth.put(250, 0, line);
HighGui.imshow("原图", truth);
HighGui.waitKey(0);
}
上面代码中,我们创建了一个byte数组,然后放到mat上就把直线显示出来了
主要用到了Mat中的put方法:
put(250,0,line)
250 标识第250行
0 标识所有的列(特殊 0标识所有的列)
line标识 数组
三.图片反色练习
public static Mat MatInvert(Mat mat) {
int channels = mat.channels();
int b, g, r;
for (int j = 0; j < mat.height(); j++) {
for (int i = 0; i < mat.width(); i++) {
byte[] temp = new byte[channels];
mat.get(j, i, temp);
b = temp[0] & 0xff;
g = temp[1] & 0xff;
r = temp[2] & 0xff;
// 修改像素点
b = 255 - b;
g = 255 - g;
r = 255 - r;
// 写入
temp[0] = (byte) b;
temp[1] = (byte) g;
temp[2] = (byte) r;
mat.put(j, i, temp);
}
}
return mat;
}
public static Mat MatInvert2(Mat mat) {
int channels = mat.channels();
byte[] temp = new byte[channels * mat.width()];
for (int j = 0; j < mat.height(); j++) {
mat.get(j, 0, temp);
for (int i = 0; i < temp.length; i++) {
int pv = temp[i] & 0xff;
temp[i] = (byte) (255 - pv);
}
mat.put(j, 0, temp);
}
return mat;
}
public static Mat MatInvert3(Mat mat) {
int channels = mat.channels();
byte[] temp = new byte[channels * mat.width() * mat.height()];
mat.get(0, 0, temp);
for(int i=0;i<temp.length;i++) {
temp[i]=(byte)(255-temp[i]&0xff);
}
mat.put(0, 0, temp);
return mat;
}
测试结果:
上面主要学习的是Mat的put方法和get方法,获取到具体的像素点,或者获取到行像素,全部的像素存入byte数组中,通过改变byte数组的值,来实现图片的改变,特别记住的是put( 0,0,byte) 里面的0 是所有的行或者列
希望对你有所帮助