개발자 승학

OpenCV 이미지 픽셀 수 구하기(전체,흑색,백색) 본문

it/OpenCV

OpenCV 이미지 픽셀 수 구하기(전체,흑색,백색)

유승학 2019. 4. 3. 09:39

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include
#include 
using namespace std;
using namespace cv;

int main()
{
// Mat : opencv에서 가장 기본이 되는 데이터 타입으로 행렬(Matrix) 구조체
// 원본 이미지
Mat original_Image; 
original_Image = imread("Rectangle3.png", IMREAD_COLOR);
if (original_Image.empty())
{
cout << "이미지를 열 수 없습니다." << endl;
return -1;
}

// 그레이 이미지
Mat gray_image;
if (original_Image.channels() == 3)
cv::cvtColor(original_Image, gray_image, CV_BGR2GRAY);

// 이미지의 히스토그램이 특정영역에 너무 집중되어 있으면 contrast가 낮아 좋은 이미지라 할 수 없다.
// 전체 영역에 골고루 분포가 되어 있을때 좋은 이미지라 할 수 있으므로
// 특정영역에 분포되어 부분을 골고루 분포하도록 하는 작업.
equalizeHist(gray_image, gray_image);

// 이진화 이미지
// 모든 픽셀을 흑과 백(0과1)으로만 표현하기 위해
Mat binary_image;
threshold(gray_image, binary_image, 127, 255, CV_THRESH_BINARY_INV);

vector hierarchy;
vector<vector > contours;
findContours(binary_image.clone(), contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

// 흑색 픽셀과 백색 픽셀을 구하기 위해 
Mat mask;
mask = Mat::zeros(binary_image.size(), CV_8UC1);


for (int i = 0; i < contours.size(); i++)
{
drawContours(mask, contours, i, cv::Scalar(255, 255, 255), CV_FILLED, 8, hierarchy, 0, Point());
}

int iBlackPixel = 0;
int iWhitePixel = 0;
for (int x = 0; x < mask.rows; x++)
{
for (int y = 0; y < mask.cols; y++)
{
// 흰색 픽셀값은 255
if (mask.at(x, y) == 255)
{
iWhitePixel++;
}
else
{
iBlackPixel++;
}
}
}

cout << "All pixel : " << mask.total() << endl;
cout << "Black pixel : " << iBlackPixel << " White pixel : " << iWhitePixel << endl;
cv::imshow("Original Image", original_Image);
waitKey(0);
}

'it > OpenCV' 카테고리의 다른 글

OpenCV 이미지 이진화  (0) 2019.04.03
OpenCV 이미지 불러오기  (0) 2019.04.03
Comments