显示来自greyimage的像素块

时间:2013-11-11 15:26:38

标签: c++ opencv

我有一个灰色图像,我想从每8个像素中获取像素值   (像素块)   如何从灰色图像中读取这个像素块?   这是我做的代码

void main()

{
 Mat img = imread("Frame.jpg",0);

if(!img.data)   
    std::cout << "error";

double minVal, maxVal;
minMaxLoc(img,&minVal,&maxVal,NULL,NULL);
double Threshold = 0.5 * (minVal + maxVal);
int i,j;
for (i=0;i<img.rows;i++)
    for(j=0;j<img.cols;j++)
        unsigned char Pixel = img.at<unsigned char>(i,j);




namedWindow( "Display window", CV_NORMAL );// Create a window for display.
    imshow( "Display window", img );
 waitKey(0);    

     }

谢谢

1 个答案:

答案 0 :(得分:0)

确切地确定您要执行的操作,但是,如果您尝试获取中心像素周围的像素,则可以通过调整索引手动执行此操作。如果像素周围的块标记为:

0 1 2
3 P 4
5 6 7

你可以通过循环

来获得0-7的值
for (i=1;i<img.rows-1;i++){
    for(j=1;j<img.cols-1;j++){
        unsigned char Pixel = img.at<unsigned char>(i,j);
        unsigned char Pixel_0 = img.at<unsigned char>(i-1,j-1);
        unsigned char Pixel_1 = img.at<unsigned char>(i,j-1);
        unsigned char Pixel_2 = img.at<unsigned char>(i+1,j-1);
        unsigned char Pixel_3 = img.at<unsigned char>(i-1,j);
        unsigned char Pixel_4 = img.at<unsigned char>(i+1,j);
        unsigned char Pixel_5 = img.at<unsigned char>(i-1,j+1);
        unsigned char Pixel_6 = img.at<unsigned char>(i,j+1);
        unsigned char Pixel_7 = img.at<unsigned char>(i+1,j+1);
    }
}

或者,如果您想将整个窗口子集化为新的cv :: Mat,您可以使用ROI。

for (i=1;i<img.rows-1;i++){
    for(j=1;j<img.cols-1;j++){
        unsigned char Pixel = img.at<unsigned char>(i,j);
        cv::Mat ROI = img(cv::Rect(i-1,j-1,3,3));
    }
}

注意,对于这两种情况,循环仅在1&gt; rows-1和1-&gt; cols-1之间,你必须分别处理边界情况。