I have found many examples in opencv of sending a mat through socket from java to java or c++, but I can't get it to work on python.
The server code:
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", out, bytemat);
byte[] bytes = bytemat.toArray();
r.write(String.valueOf(bytes.length));
Log.d(TAG, String.valueOf(bytes.length));
r.write(bytes);
The python code:
def recvall(sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
length = recvall(camera_socket, 5)
if not length:
continue
print length
data = recvall(camera_socket, int(length))
if not data:
continue
nparr = np.fromstring(data, np.uint8)
frame = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_UNCHANGED)
window = cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
cv2.imshow('frame', frame)
The weird part is that imdecode returns None always. I just can't get it to work. PS: the java client works using ObjectInputStream
----EDIT---- Thanks all for advices, I've replaced the byte stream with predefined bytes and discovered that Java was sending some headers when sending bytes because it was using ObjectOutputStream.
Now the java code for writing to socket is:
DataOutputStream oos = null;
try {
oos = new DataOutputStream(os);
oos.write(byteImage);
} catch (Exception e) {
Log.e(TAG, "Error while writing to OutputStream", e);
cancel();
setState(STATE_NONE, this.type);
}