5. 把一幅彩色图像的H、S、I分量单独显示。

#include <cv.h>
#include <highgui.h> 
# include <math.h>
#define M_PI 3.1415
void RGB_to_HSI(IplImage *src, IplImage *dst);
int main(void)
{
    IplImage * oo  = cvLoadImage   ("6013202130.jpg", 1);
    IplImage * xx  = cvCreateImage  (cvGetSize(oo), 8, 1);
    RGB_to_HSI(oo, xx);
    cvNamedWindow("原图", 1);
    cvNamedWindow("HSI", 1);
    cvShowImage("原图", oo);
    cvShowImage("HSI" , xx);
    cvWaitKey(0);
    cvReleaseImage(&xx);
    cvReleaseImage(&oo);
    return 0;
}

void RGB_to_HSI(IplImage *src, IplImage *dst)
{
    int i, j;
    double b, g, r, numm, den, min, theta, H, S, I;
    CvScalar s0;
    for (i = 0; i<src->height; i++)
    for (j = 0; j<src->width; j++)
    {

        s0 = cvGet2D(src, i, j);
        b = s0.val[0] / 255;//rgb归一化
        g = s0.val[1] / 255;
        r = s0.val[2] / 255;
        //几何推导法转换
        numm = 0.5*((r - g) + (r - b));
        den = sqrt((r - g)*(r - g) + (r - b)*(g - b));
        if (den == 0)
            H = 0;
        else
        {
            theta = acos(numm / den);
            if (b>g)
                H = (2 * M_PI - theta) / (2 * M_PI);
            else
                H = theta / (2 * M_PI);
        }
        min = (b>g) ? g : b;
        min = (min>r) ? r : min;
        den = r + g + b;
        if (den == 0)
            S = 0;
        else
            S = 1 - 3 * min / den;
        I = (r + g + b) / 3;
        cvSet2D(dst, i, j, cvScalar(H * 180, S * 255, I * 255));
    }
}

posted @ 2016-05-06 12:40  张飞online  阅读(813)  评论(0编辑  收藏  举报