Qt魔方还原5

Qt魔方还原5

目的

用opencv识别魔方图片颜色,完成魔方初始输入,效果如下
Qt魔方还原5_第1张图片

实施

1.说明
这里只是识别一张魔方图片,里面的rgb阈值可能取得有点特殊,这部分代码没有集成到之前的里面去,是单独一个demo,如果要集成到前面的代码去,可以搜索Qt如何使用opencv即可。

2.步骤
(1)读入图片

IplImage* img = cvLoadImage("cube.jpg");

(2)灰度化

IplImage *gray = cvCreateImage(cvGetSize(img), 8, 1);
cvCvtColor(img, gray, CV_BGR2GRAY);

(3)滤波与二值化

IplImage *dst_median = cvCreateImage(cvGetSize(img), 8, 1);
cvSmooth(gray, dst_median, CV_MEDIAN, 7, 7, 0, 0);
cvThreshold(dst_median, dst_median, 100, 255, CV_THRESH_BINARY);

(4)找出魔方位置

CvSeq *pContour = NULL;
CvMemStorage* storage = cvCreateMemStorage(0);
CvBox2D s;
cvFindContours(dst_median, storage, &pContour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
CvRect rect;
for (CvSeq* c = pContour; c != NULL; c = c->h_next)
{
    rect = cvBoundingRect(pContour, 0);
    cvRectangle(img, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height),cvScalar(0, 0, 255), 2);
}

(5)提取颜色

CvScalar getAvgBGR(IplImage *img)
{
    int width = img->width;
    int height = img->height;
    double b=0, g=0, r=0;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            CvScalar s = cvGet2D(img, j, i);
            b += s.val[0];
            g += s.val[1];
            r += s.val[2];
        }
    }
    b = b / (width*height);
    g = g / (width*height);
    r = r / (width*height);
    CvScalar scalar = cvScalar(b, g, r);
    return scalar;
}

代码

https://download.csdn.net/download/gaobobo138968/10461018

你可能感兴趣的:(Qt)