501*_*ted 6 opencv image-processing javacv
在我的项目中,我希望从特定颜色的最大均匀区域获得大小(在我的示例中,它是蓝天).
我的第一个想法是转换原始图像:

到二进制图像,检测天空颜色并使用此区域创建一个遮罩:

但是如何获得这些白色像素的大小和位置?我想要一种有效的方法,如果图片在图片的上1/3处有蓝天,则表示正确.有任何想法吗?我应该创建一个"全局掩码"(参见注释中的图像3)并将其与二进制图片进行比较吗?或者有更简单的方法吗?
谢谢.
算法如下:
要将某些图像转换为另一个颜色空间,请使用cvtColor.
使用函数extractChannel提取所需的频道.
为此,我使用阈值函数,在步骤3中计算阈值(作为参数).也可以将图像转换为HSV并使用inRange检测蓝色,而不是步骤1-4.
这是我的c ++命令:
Mat inMat = imread("input.jpg"), blueMat, threshMat;
cvtColor(inMat, blueMat, CV_BGR2YCrCb);//convert to YCrCb color space
extractChannel(blueMat, blueMat, 2);//get blue channel
//find max value of blue color
//or you can use histograms
//or more complex mathod
double blueMax;
minMaxIdx(blueMat, 0, &blueMax);
blueMax *= 0.8;
//make binary mask
threshold(blueMat, threshMat, blueMax, 255, THRESH_BINARY);
//finding all blue contours:
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(blueMat, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
double maxSquare = 0;
vector<Point> maxContour;
//finding contours with biggest square:
for (size_t i=0; i<contours.size(); i++)
{
double square = contourArea(contours[i]);
if (square > maxSquare)
{
maxContour = contours[i];
maxSquare = square;
}
}
//output results:
Point center = centerPolygon(maxContour);
cout << "square = " << maxSquare << endl;
cout << "position: x: " << center.x << ", y: " << center.y << endl;
Run Code Online (Sandbox Code Playgroud)
这是centerPolygon功能:
Point centerPolygon(const vector<Point>& points)
{
int x=0, y=0;
for (size_t i=0; i<points.size(); i++)
{
x += points[i].x;
y += points[i].y;
}
return Point(x/points.size(), y/points.size());
}
Run Code Online (Sandbox Code Playgroud)
程序的输出是下一个:
square = 263525
position: x: 318, y: 208
Run Code Online (Sandbox Code Playgroud)
您可以将此代码转换为JavaCV - 请参阅本教程.
| 归档时间: |
|
| 查看次数: |
1466 次 |
| 最近记录: |