Last active
March 20, 2016 12:25
-
-
Save ruwanka/4a002888afce767f9e23 to your computer and use it in GitHub Desktop.
Find background color of an article image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <opencv\cv.h> | |
#include <opencv\highgui.h> | |
int main(int argc, char* argv[]) | |
{ | |
cv::Mat img = cv::imread("E:\\stuff\\articles\\Test Articles\\article_25.jpg", | |
CV_LOAD_IMAGE_UNCHANGED); | |
if (img.empty()) | |
{ | |
std::cout << "can not read image!" << std::endl; | |
return -1; | |
} | |
cv::cvtColor(img, img, cv::COLOR_BGR2RGB); | |
img = img.reshape(3, img.rows * img.cols); | |
img.convertTo(img, CV_32F); | |
int clusterCount = 2; | |
int dimensions = 3; | |
cv::Mat labels, centers(2, 1, CV_32F); | |
std::cout << "dimensionality " << img.dims << std::endl; | |
std::cout << "type " << (img.type() == CV_32F ? "true" : "false") << std::endl; | |
try | |
{ | |
cv::kmeans(img, | |
clusterCount, | |
labels, | |
cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 50, 30.0), | |
10, | |
cv::KMEANS_PP_CENTERS, centers); | |
} | |
catch (std::exception e) | |
{ | |
std::cout << e.what() << std::endl; | |
} | |
// dump centers | |
std::cout << "Center: \n" << centers << std::endl; | |
// output Mats | |
cv::Mat backgound(200, 200, CV_8UC3), foreground(200, 200, CV_8UC3); | |
cv::Scalar center1 = cv::Scalar(centers.at<float>(0, 2), | |
centers.at<float>(0, 1), | |
centers.at<float>(0, 0)); | |
cv::Scalar center2 = cv::Scalar(centers.at<float>(1, 2), | |
centers.at<float>(1, 1), | |
centers.at<float>(1, 0)); | |
if (center1.val[0] > center2.val[0] && | |
center1.val[1] > center2.val[1] && | |
center1.val[2] > center2.val[2]) | |
{ | |
// center 1 is background | |
backgound.setTo(center1); | |
foreground.setTo(center2); | |
} | |
else | |
{ | |
// center 2 is background | |
backgound.setTo(center2); | |
foreground.setTo(center1); | |
} | |
cv::namedWindow("background", CV_WINDOW_AUTOSIZE); | |
imshow("background", backgound); | |
cv::namedWindow("foreground", CV_WINDOW_AUTOSIZE); | |
imshow("foreground", foreground); | |
cv::waitKey(); | |
cv::destroyAllWindows(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment