什么我必须改变,我可以从数组中读取像素值?

时间:2013-11-18 13:55:16

标签: c++ opencv

我有以下代码。我从图像中读取了一个像素块,我想从每个块(数组16 * 16)中获取值。 但是,我收到了这个错误:

  

OpenCV错误:断言失败(dims< = 2&& data&&(unsigned)i0<(unsigned)size.p [0]&&(unsigned)(i1 * DataType< _Tp> :: channels)<(unsigned)(size.p [1] * channels())&&((((sizeof(size_t)<< 28)| 0x8442211)

     

((DataType< _Tp> :: depth)&((1<<< 3)-1))* 4)& 15)== elemSize1())在未知函数中,文件C:\ opencv231 \ build \ include \ opencv2 / core / mat.hpp,第537行

我应该更改哪些内容才能运行我的代码?

enum Color {White, Black}; 
Color checkBlock(Mat& img, int& i, int& j, double& T)
{
    unsigned int Sum=0;
    for(int k=0;k<16;k++)
        for(int l=0;l<16;l++)
            Sum += img.at<unsigned char>(i+k,j+l);
    double Average = Sum/256;
    std::cout << Average << std::endl;
    return (Average > T) ? (White) : (Black);
}

void main()
{
    Mat img = imread("Frame.jpg",0);
    namedWindow( "Display window", CV_NORMAL );// Create a window for display.
    if(!img.data)   
        std::cout << "error";
    // STEPS TO CONVERT TO BINARY IMAGE
    // LOAD THE IMAGE 
    cv::Mat imageMat = cv::imread("Frame.jpg", CV_LOAD_IMAGE_COLOR);

    cv::Mat grayscaleMat (imageMat.size(), CV_8U);

    //Convert BGR to Gray
    cv::cvtColor(imageMat, grayscaleMat, CV_BGR2GRAY );

    //Binary image
    cv::Mat binaryMat(grayscaleMat.size(), grayscaleMat.type());

    //Apply thresholding
    cv::threshold(grayscaleMat, binaryMat, 100, 255, cv::THRESH_BINARY);

    //Show the results
    // cv::namedWindow("Output",CV_NORMAL);
    //cv::imshow("Output", binaryMat);

    // cv::waitKey(0);

    double minVal, maxVal;
    minMaxLoc(img,&minVal,&maxVal,NULL,NULL);
    double Threshold = 0.5 * (minVal + maxVal);
    int i=4,j=4;
    Size s = img.size();
    Color old_c, new_c;
    // define the position wher i will begin to read the first row from the image 
    for (j=16*55;j<=s.height;j=j+16)
        for(i=0;i<=s.width;i=i+16)
        {
            Point x(i,j);
            Point y(i+16,j+16);
            //std::cout << x << " " << y << std::endl;
            rectangle(img, x, y, Scalar(255,0,0),3);
            Color c = checkBlock(img,i,j,Threshold);
        }

2 个答案:

答案 0 :(得分:1)

在这一行中,您使用i索引一行:

        Sum += img.at<unsigned char>(i+k,j+l);

但是,i来自哪里,显然是col的索引。

        for(i=0;i<=s.width;i=i+16)

所以第一行应该是:

Sum += img.at<unsigned char>(j+l, i+k);

为了清楚起见,at的参数是(row,col),Point的参数是(x,y),这是一个陷阱。

另外

for (j=16*55;j<=s.height;j=j+16)
    for(i=0;i<=s.width;i=i+16)
        ...
        Point y(i+16,j+16);

应该是

for (j = 16 *  55; j < s.height - 15 ; j = j + 16)
    for(i = 0; i < s.width - 15; i = i + 16)
        ...
        Point y(i + 15, j + 15);

答案 1 :(得分:0)

imread()必须包含文件的完整路径,并确保使用双破折号,例如。

cv::Mat imageMat = cv::imread(C:\\Folder\\Frame.jpg", CV_LOAD_IMAGE_COLOR);

没有必要指定grayscaleMatbinaryMat的维度或类型,因为opencv函数会为您准备它们。

在你的cvtColor函数中,它应该是CV_RGB2GRAY而不是CV_BGR2GRAY。

在你的阈值函数中,它不应该是cv :: THRESH_BINARY而是CV_THRESH_BINARY

希望这有帮助。