效果展示
实现原理
1、转化成灰度图
Mat image = imread("C:\\Users\\chenxinyu\\Desktop\\物品.jpg",IMREAD_COLOR);
if (image.empty())
return -1;
Mat outImage;
cvtColor(image, outImage, COLOR_BGR2GRAY);
2、绘制轮廓
在绘制轮廓之前,我们需要进行高斯模糊降噪。
Mat outBlur,outCanny;
GaussianBlur(outImage, outBlur,Size(3,3),1.5);
Canny(outBlur, outCanny,100,150);
减少无关噪声对轮廓的影响。
3、二值化操作
对原图像进行二值化操作,再与轮廓图相加,丰富饱满轮廓图。
Mat outThreshold;
threshold(outImage, outThreshold, 120, 255, THRESH_BINARY_INV);
Mat outThreshold1;
threshold(outImage, outThreshold1, 220, 255, THRESH_BINARY);
Mat outOr;
bitwise_or(outCanny, outThreshold, outOr);
bitwise_or(outOr, outThreshold1, outOr);
注:第二次二值化是为针对图像中白色蛋壳。
4、膨胀和腐蚀
去掉多余的线条,让图像更加饱满。
Mat outElement;
outElement=getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
morphologyEx(outOr, outOr, MORPH_CLOSE, outElement);
morphologyEx(outOr, outOr, MORPH_OPEN, outElement);
5、找轮廓、标识
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(outOr, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (size_t i = 0; i < contours.size(); i++) {
// 计算面积
double area = contourArea(contours[i]);
// 标注瑕疵
Rect bbox = boundingRect(contours[i]);
rectangle(image, bbox, Scalar(0, 0, 255), 2); // 红色边界框
}
整体代码
int demo4()
{
Mat image = imread("C:\\Users\\chenxinyu\\Desktop\\物品.jpg",IMREAD_COLOR);
if (image.empty())
return -1;
imshow("111.jpg", image);
Mat outImage;
cvtColor(image, outImage, COLOR_BGR2GRAY);
imshow("222.jpg", outImage);
////画轮廓
Mat outBlur;
GaussianBlur(outImage, outBlur,Size(3,3),1.5);
imshow("333.jpg", outBlur);
Mat outCanny;
Canny(outBlur, outCanny,100,150);
imshow("444.jpg", outCanny);
Mat outCanny1;
Canny(outImage, outCanny1, 100, 150);
imshow("text1.jpg", outCanny1);
//二值分化
Mat outThreshold;
threshold(outImage, outThreshold, 120, 255, THRESH_BINARY_INV);
imshow("555.jpg", outThreshold);
Mat outThreshold1;
threshold(outImage, outThreshold1, 220, 255, THRESH_BINARY);
imshow("text.jpg", outThreshold1);
Mat outOr;
bitwise_or(outCanny, outThreshold, outOr);
bitwise_or(outOr, outThreshold1, outOr);
imshow("666.jpg", outOr);
Mat outElement;
outElement=getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
morphologyEx(outOr, outOr, MORPH_CLOSE, outElement);
morphologyEx(outOr, outOr, MORPH_OPEN, outElement);
imshow("777.jpg", outOr);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(outOr, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (size_t i = 0; i < contours.size(); i++) {
// 忽略小面积区域(噪声)
double area = contourArea(contours[i]);
// 标注瑕疵
Rect bbox = boundingRect(contours[i]);
rectangle(image, bbox, Scalar(0, 0, 255), 2); // 红色边界框
}
imshow("888.jpg", image);
waitKey(0);
}