使用opencv寻找某个物体的最小垂直矩形,选定图片里的物体所在区域,复制给新图片,再对新图片进行操作,可以减少运算复杂度
寻找矩形的原理是,先寻找图片里物体的边缘,然后从边缘来寻找矩形。这个代码里以vector向量Contours保存边缘数据,以BoundRectangle保存矩阵数据。
int main()
{
Mat Picture = imread("pic.jpg");
Mat PicColor = Picture.clone();
/* 首先转化为二值图 */
Mat PicBi;
int thresh = 120; //threshold 阈值
int maxval = 255;
cvtColor(PicColor, PicBi, CV_BGR2GRAY);
threshold(PicBi, PicBi, thresh, maxval, CV_THRESH_BINARY);
/* 对二值图寻找最小外接垂直矩阵,挑其中最大的那个矩阵 */
vector<Rect>BoundRectangle;
Point tl, br;
tl.x = 0;
tl.y = 0;
br.x = 0;
br.y = 0;
vector<vector<Point>>Contours;
vector<Vec4i> hierarchy;
//寻找边缘,把边缘的点放到容器中
findContours(PicBi, Contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
//从边缘容器中寻找最小外接垂直矩形
//函数boundingRect用来寻找矩阵,返回值是Rect值
for (int i = 0; i < Contours.size(); i++)
{
BoundRectangle.push_back(boundingRect(Mat(Contours[i]))); //外接矩形
/* 寻找最大的外接垂直矩形 */
int length;
length = (BoundRectangle[i].br().x - BoundRectangle[i].tl().x) ^ 2 + (BoundRectangle[i].br().y - BoundRectangle[i].tl().y) ^ 2;
int oldlength;
oldlength = (br.x - tl.x) ^ 2 + (br.y - tl.y) ^ 2;
if (length > oldlength)
{
tl = BoundRectangle[i].tl();
br = BoundRectangle[i].br();
}
}
//把最大的那个矩形画在图片中
Mat PicBiRectangle;
PicBiRectangle = PicBi.clone();
rectangle(PicBiRectangle, tl, br, WHITENESS, 2, 8, 0);
/* 把最小矩形的图像,外面加两层像素后复制到另一个Mat容器 */
int width = (br.y - tl.y) + 1 + 4;
int height = (br.x - tl.x) + 1 + 4;
Mat PicSmall(height, width, CV_8UC1, BLACKNESS);
PicSmall = 0;
//抠图
PicSmall = PicBi(Rect(tl.x-2, tl.y-2, height, width));
/* Debug Window */
namedWindow("BiPic", 0);
namedWindow("OrdinaryPic", 0);
namedWindow("SmallPic", 0);
imshow("BiPic", PicBiRectangle);
imshow("OrdinaryPic", PicColor);
imshow("SmallPic", PicSmall);
waitKey(0);
system("PAUSE");
}