2

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!

3
  • 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. Commented Dec 4, 2019 at 10:45
  • An OpenCV image is just a Numpy array in Python, so you could look at this... stackoverflow.com/a/55313342/2836621 Commented Dec 4, 2019 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? Commented Dec 5, 2019 at 1:28

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.