5

I am trying to create a sepia effect. This is the code I am trying:

    Mat image_copy;
    cvtColor(image, image_copy, CV_BGRA2BGR);

    Mat kern = (Mat_<char>(4,4) <<  0.272, 0.534, 0.131, 0,
                0.349, 0.686, 0.168, 0,
                0.393, 0.769, 0.189, 0,
                0, 0, 0, 1);
    cv::transform(image_copy, image, kern);

But it doesn't work. I get a black image. No error, no exception, just black image. Any ideas?

I have tried applying different kernels and they do work. For example:

    Mat kern = (Mat_<char>(4,4) <<  10, 0, 0, 0,
                0, 10, 0, 0,
                0, 0, 10, 0,
                0, 0, 0, 10);
    cv::transform(image_copy, image, kern);
    image += cv::Scalar(10, 10, 10, 0);

Please help.

karlphillip
  • 92,053
  • 36
  • 243
  • 426
Richard Knop
  • 81,041
  • 149
  • 392
  • 552

1 Answers1

6

It seems you are creating a kernel of char values but trying to store float values.

Make sure to declare the kernel with the same data type as the values you want to store:

#include <cv.h>
#include <highgui.h>

#include <iostream>

int main()
{
    cv::Mat image = cv::imread("test.jpg");
    if (!image.data)
    {
        std::cout << "!!! Failed imread" << std::endl;
        return -1;
    }

    cv::Mat image_copy = image.clone();

    cv::Mat kern = (cv::Mat_<float>(4,4) <<  0.272, 0.534, 0.131, 0,
                                             0.349, 0.686, 0.168, 0,
                                             0.393, 0.769, 0.189, 0,
                                             0, 0, 0, 1);

    cv::transform(image_copy, image, kern);

    cv::imshow("sepia", image);
    cv::waitKey(0);

    return 0;
}
karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • @karlphillip If we try to make our own filters then do we need to strong in photoshop ? or we can simply change values by hit and trial method ? and second thing that can we use the same thing in native c++ ? – AHF Mar 22 '14 at 14:17
  • @Ahmad You don't need photoshop. Play around with the numbers until they make sense. :) – karlphillip Mar 22 '14 at 15:44
  • 1
    @karlphillip Well i often get help from your answers and discuss you with my friends and at job too that some one name "karlphillip" on stackoverflow is very genius in opencv :) thankyou – AHF Mar 23 '14 at 07:45
  • @Ahmad You are too kind, sir. ;) – karlphillip Mar 23 '14 at 08:14
  • I tried to use this approach in C++ for my mobile app but the result was either a totally white image (not black as in the question) or a very bright image when using filter2d instead of transform. Maybe you might check my question? @karlphillip https://stackoverflow.com/questions/68312285/opencv-4-5-2-c-apply-matrix-44-to-image-and-write-to-file-results-in-wh – goldensoju Jul 09 '21 at 06:42