23.11.15 (수) 40일차
이진화 처리 (src_bin)
윤곽선 drawing
#pragma once
#include "ISP.h"
int main()
{
std::string fileName = "../KCCImageNet/stop_img.png";
cv::Mat src_color = cv::imread(fileName, cv::IMREAD_ANYCOLOR);
uchar* pData = src_color.data;
size_t width = src_color.cols;
size_t height = src_color.rows;
Mat src_bin = Mat::zeros(Size(width, height), CV_8UC1);
uchar* pDataBin = src_bin.data;
Scalar lower_red = Scalar(40, 30, 190);
Scalar upper_red = Scalar(100, 100, 255);
inRange(src_color, lower_red, upper_red, src_bin);
RNG rng(12345);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(src_bin, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
Mat drawing = Mat::zeros(src_bin.size(), CV_8UC3);
Scalar color = Scalar(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
drawContours(drawing, contours, 0, color, 2, LINE_8, hierarchy, 0);
int CoGx, CoGy;
CoGx, CoGy = 0, 0;
int x_min = width, x_max = 0, y_min = height, y_max = 0;
for (size_t n = 0; n < contours[0].size(); n++)
{
if (x_min > contours[0].at(n).x)
x_min = contours[0].at(n).x;
if (x_max < contours[0].at(n).x)
x_max = contours[0].at(n).x;
if (y_min > contours[0].at(n).y)
y_min = contours[0].at(n).y;
if (y_max < contours[0].at(n).y)
y_max = contours[0].at(n).y;
}
CoGx = (x_min + x_max) / 2;
CoGy = (y_min + y_max) / 2;
float rad = (x_max - x_min) / 2;
circle(src_color, Point(CoGx, CoGy), rad, CV_RGB(0, 255, 0), 3);
uchar* pDataMask = src_bin.data;
int sum_red = 0;
int sum_red_count = 0;
for (size_t row = 0; row < src_color.rows; row++)
{
for (size_t col = 0; col < src_color.cols; col++)
{
int index = row * src_color.cols + col;
int index_bgr = index * 3;
int red = pData[index_bgr + 2];
int mask = pDataMask[index];
if (red > 0 && mask == 255)
{
sum_red += red;
sum_red_count++;
}
}
}
float avg_brightness_red = sum_red / sum_red_count;
double area = contourArea(contours[0]);
double arcLen = arcLength(contours[0], true);
string msg;
msg = format("area = %.1f", area);
putText(src_color, msg, Point(x_max, y_max + 30 * 0), FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(10, 0, 10), 1, 8);
msg = format("Len = %.1f", arcLen);
putText(src_color, msg, Point(x_max, y_max + 30 * 1), FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(10, 0, 10), 1, 8);
msg = format("x, y = %d, %d", CoGx, CoGy);
putText(src_color, msg, Point(x_max, y_max + 30 * 2), FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(10, 0, 10), 1, 8);
msg = format("Radius = %.1f", rad);
putText(src_color, msg, Point(x_max, y_max + 30 * 3), FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(10, 0, 10), 1, 8);
msg = format("Avg_red = %.1f", avg_brightness_red);
putText(src_color, msg, Point(x_max, y_max + 30 * 4), FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(10, 0, 10), 1, 8);
return 1;
}