Is there a way to find the maximum intensity element of each object in an image that contains multiple objects using opencv? The objects is supposed to be books. I want to find the dominate color for each book. I used contours to do so, but it didn't work. The function that finds the maximum intensity element:
int max_intensity_element(Mat image){
// allcoate memory for no of pixels for each intensity value
int histogram[256];
// initialize all intensity values to 0
for(int i = 0; i < 255; i++)
{
histogram[i] = 0;
}
for(int i = 0; i < 255; i++)
{
cout<< histogram[i] ;
}
// calculate the no of pixels for each intensity values
for(int y = 0; y < image.rows; y++)
for(int x = 0; x < image.cols; x++)
histogram[(int)image.at<uchar>(y,x)]++;
// draw the histograms
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound((double) hist_w/256);
Mat histImage(hist_h, hist_w, CV_8UC1, Scalar(255, 255, 255));
// find the maximum intensity element from histogram
int max = histogram[0];
int index;
for(int i = 1; i < 256; i++){
if(max < histogram[i]){
max = histogram[i];
index=i;
}
}
return index;
}
Code in main:
Mat image = imread("boo2.png");
Mat image2 = imread("boo.png");
int index, index2;
CvMemStorage* storage = NULL;
//////////////////////////////////////////////////////////////////////////
//Step 1
//Load Reference Image
IplImage * R;
int thresh = 120;
R = cvLoadImage("boo.png", 0);
//Load Target Image
IplImage * T;
T = cvLoadImage("boo2.png", 0);
//////////////////////////////////////////////////////////////////////////
//step 2
storage = cvCreateMemStorage(0);
//R contour
CvSeq* contours = 0;
cvThreshold(R, R, thresh, 255, CV_THRESH_BINARY);
cvFindContours( R, storage, &contours );
cvZero(R);
if( contours ){
cvDrawContours(
R,
contours,
cvScalarAll(255),
cvScalarAll(255),
8, CV_FILLED );
}
//////////////////////////////////////////////////////////////////////////
//Step 3
CvSeq* contour_ptr2= contours;
while( (contour_ptr2!= NULL) ) {
index2=max_intensity_element(image2);
cout<<index2<<endl;
contour_ptr2= contour_ptr2->h_next;
}
//////////////////////////////////////////////////////////////////////////
//T contour
CvSeq* contours2 = 0;
cvThreshold(T, T, thresh, 255, CV_THRESH_BINARY);
cvFindContours(T, storage, &contours2 );
cvZero(T);
if( contours2 ){
cvDrawContours(
T,
contours2,
cvScalarAll(255),
cvScalarAll(255),
8, CV_FILLED );
}
//////////////////////////////////////////////////////////////////////////
//Step 3
CvSeq* contour_ptr = contours2;
while( (contour_ptr != NULL) ) {
index=max_intensity_element(image);
cout<<index <<endl;
contour_ptr = contour_ptr->h_next;
}
//////////////////////////////////////////////////////////////////////////
if (index==index2)
{
cout<<"match";
}
else
{
cout<<" not match";
}
waitKey();
return 0;
}