我正在尝试将Opencv Mat对象从我的Android设备发送到我的服务器(PC)。
现在,我使用以下代码将mat对象转换为字节数组并发送到我的服务器。
public void send (final Mat mat) {
new Thread( "Send Thread"){
public void run(){
try{
if (socket!=null ){
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
byte[] byte_array = new byte[(int) (mat.total() * mat.channels())];
mat.get(0, 0, byte_array);
int size = byte_array.length;
int width = (int)mat.size().width;
int height = (int)mat.size().height;
dOut.writeLong(size);
dOut.writeInt(width);
dOut.writeInt(height);
dOut.write(byte_array);
dOut.flush();
}
} catch( Exception e){
e.printStackTrace();
}
}
}.start();
}
通过以下代码接收数据
public void receiveTCP() throws IOException {
new Thread() {
public void run() {
BufferedReader br = null;
DataInputStream dis = null;
try {
br = new BufferedReader(new InputStreamReader(receiveSocket.getInputStream()));
dis = new DataInputStream(receiveSocket.getInputStream());
while(true){
int size = dis.readInt();
int width = dis.readInt();
int height = dis.readInt();
imageByteArray = new byte[(int) size];
dis.readFully(imageByteArray, 0, size);
Mat mat = convertByteArrayToMat(imageByteArray, width, height);
try {Highgui.imwrite(System.currentTimeMillis()+".png",mat);
} catch (Exception e) {
e.printStackTrace();
}
imageByteArray = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
public static Mat convertByteArrayToMat(byte[] imageByteArray, int width, int height) {
Mat mat = new Mat(width, height, CvType.CV_8UC4);
mat.put(0, 0, imageByteArray);
return mat;
}
但是,图像无效。
通过TCP发送mat对象的正确方法是什么?