Arun Kumar
Arun Kumar

Reputation: 694

OpenCV Conversion from cv::Mat -> std::string -> cv::Mat results in unexpected side effects

I am trying to convert an input image to string and then back to image like a complete cycle. I get Clang-Tidy: Use of a signed integer operand with a binary bitwise operator warning with an unexpected side effect (explained in screenshots below) when I try to specify CV_8UC3 or CV_8UC1 based on my knowledge about the input image. I am not sure what this means?

I am already aware of a similar such question in a different context. But I am not sure how is my case related to that question.

This is my code :

int main (int argc, char *argv[]) {
    bool color = argv[1];
    cv::Mat img = cv::imread("../images/input.jpg", color);
    std::string img_str(img.begin<unsigned char>(), img.end<unsigned char>());
    auto* buffer = (unsigned char *) img_str.c_str();
    // Complaint happens at this line below
    cv::Mat dummy = cv::Mat(img.rows, img.cols, color ? CV_8UC3 : CV_8UC1, buffer);
    cv::imwrite("../images/output.jpg", dummy);
    return 0;
}

Input image:

enter image description here

When color == CV_8UC3:

enter image description here

When color == CV_8UC1

enter image description here

Expected behavior

Color image (replica of input image), when color == CV_8UC3

Grayscale image of input image, when color == CV_8UC1

Upvotes: 0

Views: 431

Answers (1)

Arun Kumar
Arun Kumar

Reputation: 694

I solved this issue myself by converting the image <-> string <-> image in an alternative way like below :

std::string ImageToString(const cv::Mat &img) {
    cv::Mat1b linear_img(img.reshape(1));
    return std::string(linear_img.begin(), linear_img.end());
}

After this the converted string/ images are perfect.

Upvotes: 1

Related Questions