Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble porting RGB2CMYK method from c++ to java

Tags:

java

c++

opencv

I am trying to convert a method from c++ to java. Here is the method:

void rgb2cmyk(cv::Mat& src, std::vector<cv::Mat>& cmyk)
{
    CV_Assert(src.type() == CV_8UC3);

    cmyk.clear();
    for (int i = 0; i < 4; ++i)
       cmyk.push_back(cv::Mat(src.size(), CV_32F));

    for (int i = 0; i < src.rows; ++i)
    {
        for (int j = 0; j < src.cols; ++j)
        {
            cv::Vec3b p = src.at<cv::Vec3b>(i,j);

            float r = p[2] / 255.;
            float g = p[1] / 255.;
            float b = p[0] / 255.;
            float k = (1 - std::max(std::max(r,g),b));

            cmyk[0].at<float>(i,j) = (1 - r - k) / (1 - k); 
            cmyk[1].at<float>(i,j) = (1 - g - k) / (1 - k);
            cmyk[2].at<float>(i,j) = (1 - b - k) / (1 - k);
            cmyk[3].at<float>(i,j) = k;
        }
    }
}

Problem is with the methods of OpenCv. Here is some detail:

  1. I didn't find CV_Assert method in java. dont know any alternate for that.
  2. cmyk.push_back is replaced with cmyk[i].pushback
  3. i have used Mat replacing cv::Vec3b, it is shows no error
  4. std::max is replaced with Math.max
  5. issue is assignment to cmyk[0].at<float>(i,j)

Do any one have suggestion or any better approach of changing this method to java.

Thanks in advance for help....

Edit

What i did

public void rgb2xmyk(Mat src,Mat[] cmyk)
{
    //CV_Assert(src.type() == CV_8UC3);
    //cmyk.clear();
    for (int i = 0; i < 4; ++i)
        cmyk[i].push_back(new Mat(src.size(), CvType.CV_32F));

    for (int i = 0; i < src.rows; ++i)
    {
         for (int j = 0; j < src.cols; ++j)
         {
             double[] p = src.get(i,j);
             float r = (float) (p[2] / 255.);
             float g = (float) (p[1] / 255.);
             float b = (float) (p[0] / 255.);
             float k = (1 - Math.max(Math.max(r,g),b));

             cmyk[0].at<float>(i,j) = (1 - r - k) / (1 - k); 
             cmyk[1].at<float>(i,j) = (1 - g - k) / (1 - k);
             cmyk[2].at<float>(i,j) = (1 - b - k) / (1 - k);
             cmyk[3].at<float>(i,j) = k;
        }
    }
}
like image 433
Saghir A. Khatri Avatar asked Aug 12 '15 09:08

Saghir A. Khatri


1 Answers

You must make sure that cmyk array of Mat has size=4. In the for loop, I suggest you use setTo:

for (int i = 0; i < 4; ++i)
    cmyk[i].setTo(new Mat(src.size(), CvType.CV_32F));

in the nested for loops, where you fill your cmyk, I would use put method

cmyk[0].put(i,j,new Float[] {(1 - r - k) / (1 - k)});
cmyk[1].put(i,j,new Float[] {(1 - g - k) / (1 - k)});
cmyk[2].put(i,j,new Float[] {(1 - b - k) / (1 - k)});
cmyk[3].put(i,j,new Float[] {k});

...hope this helps

like image 102
Tawcharowsky Avatar answered Sep 22 '22 16:09

Tawcharowsky