Ask Your Question

Revision history [back]

The structure should be as follows: Load image -> convert to HSV -> implement the stated algorithm on the H channel -> calculate the histogram on the new image.

I have quickly put some code together to demonstrate how I would do this; I hope it is what you are after. I have only implemented the basic structure where you can go through and add/tweak what you need. This is only a guide, if you need anything explained in more detail feel free to ask.

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

int main( int argc, char** argv )
{
  //Load image
  Mat src = imread( argv[1] );
  if( !src.data )
  { return -1; }

  Mat img = imread(argv[1]);
  Mat img_hsv;

  //convert to HSV
  cvtColor(img, img_hsv, CV_BGR2HSV);

  //allocate memory for hue distance image
  Mat distance_hue_img(img_hsv.rows, img_hsv.cols, CV_8UC1); 

  //implement hue distance calculation
  uchar* distance_hue_img_ptr = distance_hue_img.data;
  uchar* img_hsv_ptr = img_hsv.data;
  //iterate through image
  for(int y = 1; y < img_hsv.rows; ++y) for(int x = 1; x < img_hsv.cols; ++x)
  {
    /*-----------------insert your algorithim code-----------------*/
     /*----------------- below is just an example -----------------*/

    //subtract bottom pixel from top pixel
    int temp_value_y = abs(img_hsv_ptr[((y-1)*img_hsv.cols+3)+(x*3)+0] - img_hsv_ptr[((y+1)*img_hsv.cols+3)+(x*3)+0]);
    //subtract right pixel from left pixel
    int temp_value_x = abs(img_hsv_ptr[(y*img_hsv.cols+3)+((x-1)*3)+0] - img_hsv_ptr[(y*img_hsv.cols+3)+((x+1)*3)+0]);      

    //applying average of x and y, should probably use sqrt(x^2+y^2)
    int temp_value = (temp_value_y+temp_value_x)/2;

    //apply hue wrap around, opencv hue is between 0 to 179 but your algorithim was between 0 to 359
    if(temp_value > 90)
       distance_hue_img_ptr[(y*img_hsv.cols)+x] = 180-temp_value;
    else
        distance_hue_img_ptr[(y*img_hsv.cols)+x] = temp_value;
 }

  //get histogram of distance_hue_img
  Mat histogram;
  /*-----------------insert histogram code here-----------------*/

  imshow("img", img);
  imshow("hue_img", distance_hue_img);
  imshow("histogram", histogram);

  waitKey(0);

  return 0;
}