简体   繁体   English

如何获得图像中像素的颜色(灰色)?

[英]How can I get the color of pixels in my image (load grey)?

I am using this code to print the intensity of OpenCV Mat pixels. 我正在使用此代码来打印OpenCV Mat像素的强度。 However, I am getting character printed on the console instead of values between 0 and 250: 但是,我正在控制台上打印字符,而不是0到250之间的值:

image1 = imread(nameJpg, 0);
image2 = imread(lastJpg, 0);
for (int j = 0; j < image1.rows-10; j += 1){
    for (int i = 0; i < image1.cols-10; i += 1) {
        std::cout << "" << image1.at<uchar>(i, j) << "    " <<i mage1.at<uchar>(i, j)<<"\n";
    }
}

How can I solve this problem? 我怎么解决这个问题?

You want to cast it to int, such as: 您想要将其强制转换为int,例如:

(int)image.at<uchar>(i, j)

You can test this by referring to the ASCII table . 您可以通过参考ASCII表进行测试

Edit 编辑

The source of the bug you're mentioning is from how you access the pixel. 您提到的错误的来源是如何访问像素的。 i should be for the rows, and j for the columns. 我应该是行,而j应该是列。

for (int i = 0; i < src.rows; i++) {
    for (int j = 0; j < src.cols; j++)
        cout << (int)src.at<uchar>(i, j) << " ";
    cout << endl;
}

In gray image, the pixel intensity is between 0 and 255 not 250. 在灰度图像中,像素强度在0到255之间,而不是250。

If you mean that you want to get the value of a certain pixel, you may use this: 如果您想获取某个像素的值,则可以使用以下方法:

auto image=cv::imread(path,CV_LOAD_IMAGE_GRAYSCALE);
auto pixel_value=image.at<uchar>(row_idx,col_idx);

After OP's edit: 编辑OP之后:

If you want to get number instead of character while printing, use this instead: 如果要在打印时获取数字而不是字符,请改用以下方法:

auto pixel_value= static_cast<unsigned int>(image.at<uchar>(row_idx,col_idx));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM