Skip to content

Instantly share code, notes, and snippets.

@ilomon10
Created February 27, 2020 05:52
Show Gist options
  • Save ilomon10/ad86ac4ccd6fcb2925a57593438a366b to your computer and use it in GitHub Desktop.
Save ilomon10/ad86ac4ccd6fcb2925a57593438a366b to your computer and use it in GitHub Desktop.
Send image as base64 buffer from client (python opencv) to server (nodejs) using SocketIO
import cv2
import socketio #python-socketio by @miguelgrinberg
import base64
sio = socketio.Client()
sio.connect('http://x.x.x.x:xxxx)
cam = cv2.VideoCapture(0)
while (True):
ret, frame = cam.read() # get frame from webcam
res, frame = cv2.imencode('.jpg', frame) # from image to binary buffer
data = base64.b64encode(frame) # convert to base64 format
sio.emit('data', data) # send to server
cam.release()
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var sizeof = require('object-sizeof');
app.get('/', function (req, res) {
res.send('running');
})
io.on('connection', function (socket) {
socket.on('data', function (data) { // listen on client emit 'data'
var ret = Object.assign({}, data, {
frame: Buffer.from(data.frame, 'base64').toString() // from buffer to base64 string
})
io.emit('data', ret); // emmit to socket
})
})
http.listen(3000, function () {
console.log('listening on *:3333');
})
@nitin-bommi
Copy link

How do you do the same in reverse? (send an image from node to py)

@ilomon10
Copy link
Author

How do you do the same in reverse? (send an image from node to py)

just emit frame to python through socket and parse buffer frame.

@alabach
Copy link

alabach commented Apr 17, 2021

I'm working on a project and I need to send image by node js to python function and this function return 1 or 0
plz can you help me !!

@ilomon10
Copy link
Author

I'm working on a project and I need to send image by node js to python function and this function return 1 or 0
plz can you help me !!

@alabach if you need image on python you just emit image frame to python through socket and parse that buffer to frame, if you just need condition "is image was there" you dont need to send image to target, you just emit/send boolean to target.

@anubhav17T
Copy link

The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefine

I am receiving this error

@ilomon10
Copy link
Author

ilomon10 commented Apr 30, 2021

@paul2048
Copy link

Thanks! This is the only way I could send an image to the client through sockets.

@sadimoodi
Copy link

@paul2048 @ilomon10 i can not get the code to work, my node js server does not recieve the image, i tested with a string it worked but not with an image, i am using excatly the same code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment