I am trying to detect the biggest rectangulare shape in the image (TV screen detection) but first I want to detect all rectangular shapes using Hough Lines (findCounturs didn't work so well for my case). I've managed to extract HoughLines and all of the corners, but how can I extract rectangulars from this? (I'm new to OpenCV and I want to learn)
here is my code:
Mat src = imread("image.jpg"):
cv::Mat bw;
src.copyTo(bw);
cv::cvtColor(src, bw, CV_BGR2GRAY);
cv::blur(bw, bw, cv::Size(3, 3));
cv::Canny(bw, bw, 100, 100, 3);
std::vector<cv::Vec4i> lines;
cv::HoughLinesP(bw, lines, 1, CV_PI/180, 70, 30, 10);
// Expand the lines
for (int i = 0; i < lines.size(); i++)
{
cv::Vec4i v = lines[i];
lines[i][0] = 0;
lines[i][1] = ((float)v[1] - v[3]) / (v[0] - v[2]) * -v[0] + v[1];
lines[i][2] = src.cols;
lines[i][3] = ((float)v[1] - v[3]) / (v[0] - v[2]) * (src.cols - v[2]) + v[3];
}
std::vector<cv::Point2f> corners;
for (int i = 0; i < lines.size(); i++)
{
for (int j = i+1; j < lines.size(); j++)
{
cv::Point2f pt = computeIntersect(lines[i], lines[j]);
if (pt.x >= 0 && pt.y >= 0)
corners.push_back(pt);
}
}
and the used function above:
Point2f computeIntersect(cv::Vec4i a,
cv::Vec4i b)
{
int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3], x3 = b[0], y3 = b[1], x4 = b[2], y4 = b[3];
float denom;
if (float d = ((float)(x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)))
{
cv::Point2f pt;
pt.x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
pt.y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;
return pt;
}
else
return cv::Point2f(-1, -1);
}