可以遍歷槽像素這樣的:
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
}
原因downvote。沒有測試圖像,你還沒有開始學習opencv。沒有你提供的代碼,這讓我懷疑你已經付出了適當的努力,谷歌「如何在opencv迭代圖像」。如果你擊敗了你的項目的每一個需求,你會發現在stackoverflow,谷歌等豐富的資源等。從這裏學習一些教程opencv:http://docs.opencv.org/3.1.0/,嘗試Python,除非你是C比Python更好。我會建議安德魯高度回答,特別是在分析條形碼之前計算拐角和單應計算。 – saurabheights