场合
我有一个300列和1行的矩阵。当我cout <<
时,我得到:
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
...这是我期望/想要的形式。
问题
然而,当我遍历它时,我希望每次迭代都获得每个单值。但是,相反,我的顺序略有不同(有时它非常相似)。
代码
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs/imgcodecs.hpp"
using namespace std;
using namespace cv;
int main(){
Mat test(1,300,CV_8UC1, 255);
cout << test;
Mat frame, grayFrame,threshFrame,smaller;
VideoCapture cap(0);
while(true){
cap.read(frame);
cvtColor(frame, grayFrame, cv::COLOR_RGB2GRAY);
threshold(grayFrame, threshFrame, 160, 255, THRESH_BINARY);
smaller = threshFrame(Rect(0,0,300,1));
cout << smaller;
for(int x=0;x<smaller.cols;x++){
int color = smaller.at<Vec3b>(x,1)[0];
cout << color;
}
break;
}
}
...奇怪的输出不遵循与原始矩阵完全相同的0和255顺序:
00000000000000000000000000000000000000000000000000000000000000000000000000000000000002552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552552550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
矩阵最初有很多0,很少有255,其中循环输出有很多255,而不是从0开始。
基本上,我想循环显示首先显示的矩阵,并且对于每次迭代,获取每个值。所以0,0,255,255 ......等等。
答案 0 :(得分:2)
你在读垃圾。
at
功能需要(row, col)
,而不是(x, y)
。请记住row = y
和col = x
。
如果您的矩阵只是一行,则行索引必须为0
,而不是1
。
您的矩阵是单个无符号字符的通道,因此您需要使用at<uchar>
在实践中,使用:
uchar color = smaller.at<uchar>(0, x);
cout << int(color);
或使用索引:
uchar color = smaller.at<uchar>(x);