使用OpenCV将图像区域移动到中心

时间:2015-09-15 15:42:33

标签: c++ opencv contour

我试图将图像的一个区域移动到中心,我成功地获得了它的轮廓,我知道如何将它放在中心。 但我想要的是将轮廓内部的像素(黄色和黑色)移动到中心而不仅仅是轮廓(粉红色为CV_FILLED)。

图片:

代码:

//Then segment the image. save in  Mat crop
// ---- Center image -----
// pos :   contour interest
RotatedRect rr = fitEllipse(contours[pos]);
vector<Point>&contour  = contours[pos];
//http://stackoverflow.com/a/29467236/4595387
//difference between the centre of the image and centre of the contour
Point center = Point( crop.cols/2, crop.rows/2 );
int nX = center.x - rr.center.x;
int nY = center.y - rr.center.y;
for (size_t i=0; i< contour.size(); i++)
    {
        contour[i].x += nX;
        contour[i].y += nY;
    }
cout << "x: " << rr.center.x;
cout << "y: " << rr.center.y;
//color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0,    255));
//contour of the image to the center.
cv::drawContours(crop, contours, pos, color, CV_FILLED);

imshow("In",imagen_src);
imshow("Out",crop);

1 个答案:

答案 0 :(得分:1)

您基本上需要使用面具来玩copyTo。这些步骤在代码中进行了注释。如果您需要不同的背景颜色,只需在下面的代码中更改backgroundColor

代码:

#include <opencv2\opencv.hpp>
using namespace cv;

int main()
{
    // Read image
    Mat3b img = imread("path_to_image");

    // Convert to hsv
    Mat3b hsv;
    cvtColor(img, hsv, COLOR_BGR2HSV);

    // Threshold on yellow color (in hsv space)
    Mat1b maskOnYellow;
    inRange(hsv, Scalar(20, 100, 100), Scalar(40, 255, 255), maskOnYellow);

    // Find contours of yellow item
    vector<vector<Point>> contours;
    findContours(maskOnYellow.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    // Create a mask as a filled contour
    Mat1b mask(img.rows, img.cols, uchar(0));
    drawContours(mask, contours, 0, Scalar(255), CV_FILLED);

    // Get the bounding box of the item
    Rect box = boundingRect(contours[0]);

    // Get the roi in the input image according to the mask
    Mat3b item(img(box));

    // Create a black image (same size as the yellow item and same background bolor as result image) 
    // to copy the result of the segmentation
    Vec3b backgroundColor(0,0,0); // black
    Mat3b segmentedItem(item.rows, item.cols, backgroundColor);

    // Copy only the masked part
    item.copyTo(segmentedItem, mask(box));

    // Compute the center of the image
    Point center(img.cols / 2, img.rows / 2);

    // Create a result image
    Mat3b res(img.rows, img.cols, backgroundColor);

    // Compute the rectangle centered in the image, same size as box
    Rect centerBox(center.x - box.width/2, center.y - box.height/2, box.width, box.height);

    // Put the segmented item in the center of the result image
    segmentedItem.copyTo(res(centerBox));

    imshow("Result", res);
    waitKey();

    return 0;
}

输入:

enter image description here

结果:

enter image description here