user1198058
user1198058

Reputation: 41

Get all pixels coordinates that have same color

I want to get all pixels coordinates that have same color as one pixel

List<cv::Point> GetAllPixels(cv::Point x)
{
//imp
}

How can I do this in EmguCV or OpenCV?

Upvotes: 4

Views: 1669

Answers (2)

Lofty Lion
Lofty Lion

Reputation: 147

The answer should get you started. Also consider using Cmp function

For IplImage it may be something like this:

IplImage *img, *col_img, *mask_img;
// initialise images appropriately...
svSet(col_img, [colour of your choise]);
cvCmp(img, col_img, mask_img, CV_CMP_EQ);

Use mask_img to extract coordinates. You may find equivalent operations for cv::Mat.

Upvotes: 0

mevatron
mevatron

Reputation: 14021

Here is a possible solution using OpenCV C++:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <vector>

using namespace std;
using namespace cv;

std::vector<cv::Point> getPixelsWithColor(const cv::Mat& src, cv::Scalar targetColor)
{
    assert(src.type() == CV_8UC3);

    std::vector<cv::Point> identicalPoints;

    for(int row = 0; row < src.rows; ++row)
    {
        for(int col = 0; col < src.cols; ++col)
        {
            cv::Vec3b currPixel = src.at<cv::Vec3b>(row, col);
            if(currPixel[0] == targetColor.val[0] &&
               currPixel[1] == targetColor.val[1] &&
               currPixel[2] == targetColor.val[2])
            {
                identicalPoints.push_back(cv::Point(col, row));
            }
        }
    }

    return identicalPoints;
}

int main(int argc, char** argv)
{
    Mat squares = imread("colored_squares.png");

    const Scalar RED = Scalar(0, 0, 255); // OpenCV is BGR order...
    vector<Point> redPixelLocations;
    redPixelLocations = getPixelsWithColor(squares, RED);

    Mat redMask = Mat::zeros(squares.size(), CV_8UC1);

    vector<Point>::iterator i;
    for(i = redPixelLocations.begin(); i != redPixelLocations.end(); ++i)
    {
        redMask.at<uchar>(*i) = 255;
    }

    imshow("Squares", squares);
    imshow("Red mask", redMask);
    waitKey();

    return 0;
}

I used this input image:
enter image description here

And achieved this output image:
enter image description here

Enjoy! :)

Upvotes: 5

Related Questions