1

I want to share image between C++ and python using Redis. Now I have succeed in sharing numbers. In C++, I use hiredis as the client; in python, I just do import redis. The code I have now is as below:

cpp to set value:

VideoCapture video(0);
Mat img;
int key = 0;
while (key != 27)
{
    video >> img;
    imshow("img", img);
    key = waitKey(1) & 0xFF;

    reply = (redisReply*)redisCommand(c, "SET %s %d", "hiredisWord", key);
    //printf("SET (binary API): %s\n", reply->str);
    freeReplyObject(reply);
    img.da
}

python code to get value:

import redis

R = redis.Redis(host='127.0.0.1', port='6379')

while 1:
    print(R.get('hiredisWord'))

Now I want to share opencv image instead of numbers. What should I do? Please help, thank you!

ToughMind
  • 987
  • 1
  • 10
  • 28
  • As a alternate approach you may just share the file path from C++ and read it in Python. To save the encoding/decoding overhead, you may use `pickle` library to serialize the object. – ZdaR Dec 04 '19 at 10:45
  • An OpenCV image is just a Numpy array in Python, so you could look at this... https://stackoverflow.com/a/55313342/2836621 – Mark Setchell Dec 04 '19 at 11:17
  • I want to use C++ to save opencv image into redis and use python to read the image from redis. Any suggestions? – ToughMind Dec 05 '19 at 01:28

1 Answers1

2

Instead of hiredis, here's an example using cpp_redis (available at https://github.com/cpp-redis/cpp_redis).

The following C++ program reads an image from a file on disk using OpenCV, and stores the image in Redis under the key image:

#include <opencv4/opencv2/opencv.hpp>
#include <cpp_redis/cpp_redis>

int main(int argc, char** argv)
{
  cv::Mat image = cv::imread("input.jpg");
  std::vector<uchar> buf;
  cv::imencode(".jpg", image, buf);

  cpp_redis::client client;
  client.connect();
  client.set("image", {buf.begin(), buf.end()});
  client.sync_commit();
}

Then in Python you grab the image from the database:

import cv2
import numpy as np
import redis

store = redis.Redis()
image = store.get('image')
array = np.frombuffer(image, np.uint8)
decoded = cv2.imdecode(array, flags=1)
cv2.imshow('hello', decoded)
cv2.waitKey()
Dharman
  • 30,962
  • 25
  • 85
  • 135
Velimir Mlaker
  • 10,664
  • 4
  • 46
  • 58