我必须使用opencv从图像中找到标尺位置。我能够检测标尺的颜色(绿色)。如何从图像中读取所有像素并获得标尺的上下位置。
void findrulerPosition(cv::Mat image, int indx) {
std::stringstream ss;//create a stringstream
ss << indx;//add number to the stream
cv::Mat hsv;
cvtColor(image, hsv, CV_BGR2HSV);
String filename = OUTPUT_FOLDER + "hsv" + ss.str() + ".png";
imwrite(filename, hsv );
cv::Mat hsvbw;
inRange(hsv, cv::Scalar(30,0,0), cv::Scalar(80, 255, 255), hsvbw);
//inRange(hsv, cv::Scalar(12,255,255), cv::Scalar(23, 245, 255), hsvbw);
//inRange(image, cv::Scalar(0,64,255), cv::Scalar(0, 207, 255), hsvbw);
filename = OUTPUT_FOLDER + "hsvbw" + ss.str() + ".png";
imwrite(filename, hsvbw );
vector<vector<Point> > contours;
findContours(hsvbw.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
cv::Mat dst = Mat::zeros(image.size(), image.type());
drawContours(dst, contours, -1, Scalar::all(255), CV_FILLED);
this->cmpddst &= dst;
dst &= image;
this->cmpddst &= image;
filename = OUTPUT_FOLDER + "cmpddst" + ss.str() + ".png";
imwrite(filename, this->cmpddst );
filename = OUTPUT_FOLDER + "dst" + ss.str() + ".png";
imwrite(filename, dst );
}
答案 0 :(得分:3)
这就是我所做的:
Mat src = imread("input.png"), tmp;
cvtColor(src, tmp, CV_BGR2HSV_FULL);
inRange(tmp, Scalar(50, 50, 50), Scalar(70, 255, 255), tmp);
vector<vector<Point> > contours;
findContours(tmp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
int upY = INT_MAX, lowY = 0, upX, lowX;
for (int i=0; i<contours.size(); i++)
{
if (contourArea(contours[i]) > 100)
{
for (int j=0; j<contours[i].size(); j++)
{
if (contours[i][j].y > lowY)
{
lowY = contours[i][j].y;
lowX = contours[i][j].x;
}
if (contours[i][j].y < upY)
{
upY = contours[i][j].y;
upX = contours[i][j].x;
}
}
cout << "low = (" << lowX << ", " << lowY << ")"<< endl
<< "up = (" << upX << ", " << upY << ")"<< endl;
break;
}
}
circle(src, Point(lowX, lowY), 3, Scalar(255, 0, 255));
circle(src, Point(upX, upY), 3, Scalar(255, 0, 255));
imshow("Window", src);
waitKey();
结果如下: