Sharing Opencv image between C++ and python using Redis

Question:

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): %sn", 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!

Asked By: ToughMind

||

Answers:

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()
Answered By: Velimir Mlaker
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.