您可以像这样迭代槽像素:
uchar pixel = 0;
Mat img; // this must be grayscale image - type CV_8U
for(int i=0; i<img.rows; i++)
{
// this loop is iterating from left to right
for(int j=0; i<img.cols; j++)
{
pixel = img.at<uchar>(i,j);
// do something (e.g. sum pixels)
// OpenCV doesn't have binary image type, so usually white pixels value is 255
}
}
更好的解决方案可能是使用findContours和minAreaRect,它们应该在每条线周围创建一个矩形:
vector<vector<Point>> vecContours;
vector<Vec4i> hierarchy;
RotatedRect currentRect;
Mat binaryImage = imread(...)
// binaryImage should contain only shapes or edges, I suggest using one of these approaches:
// simple binary tresholding, try different threshold_value
threshold(binaryImage, binaryImage, threshold_value, 255, THRESH_BINARY);
// adaptiveTreshold works better when image is varying in brightness
// adjust blockSize and C (start with C=0)
adaptiveThreshold(binaryImage, binaryImage, 255, ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, blockSize, C);
// another option would be to use Canny edge detector:
// http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/canny_detector/canny_detector.html
// find external contours, binaryImage = grayscale 8-bit image
// binaryImage is modified during findContours so we create a clone
findContours(binaryImage.clone(), vecContours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
// find minAreaRect for each contour (each line)
for (size_t = 0; i < vecContours.size(); i++)
{
// filter unwanted objects (contours with less than 4 points, contours with too small area)
if (vecContours[i].size() < 4 || contourArea(vecContours[i]) < someAreaInPixels)
continue;
// you can draw contours for debugging
// drawContours(binaryImage, vecContours, i, Scalar(255,0,0), 1, 8, hierarchy, 0, Point());
RotatedRect minRect = minAreaRect(vecContours.at(i));
// now you can use minRect.size.width to determine width of the bar
// minRect contains center point, size and angle
}