OpenCV显示像素值

4
我有以下代码。当我运行程序时,屏幕上显示的是未知字符而不是像素值。我想要显示像素值。我该如何做?谢谢。
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat image = imread("/home/fd/baby.jpg");
    for( int i = 0 ; i < image.rows ; i++)
    {
        for( int j = 0 ; j < image.cols ; j++ )
        {
            if(image.type() == CV_8UC1)
            {
                image.at<uchar>(i,j) = 255;
            }
            else if(image.type() == CV_8UC3)
            {
                cout << image.at<Vec3b>(i,j)[0] << " " << image.at<Vec3b>(i,j)[1] << " " << image.at<Vec3b>(i,j)[2] << endl;

                image.at<Vec3b>(i,j)[0] = 255;
                image.at<Vec3b>(i,j)[1] = 255;
                image.at<Vec3b>(i,j)[2] = 255;

                cout << image.at<Vec3b>(i,j)[0] << " " << image.at<Vec3b>(i,j)[1] << " " << image.at<Vec3b>(i,j)[2] << endl;
            }
            else
            {
                cout << "Anknown image format" << endl;
                return 0;
            }
        }
    }
    imshow("Result İmage", image);
    waitKey(0);
}

这是结果屏幕:

输入图像描述


3
可能是重复的问题:为什么 std::cout 不能打印正确的 int8_t 数值? - Alan Stokes
但是你知道像素图像的值在0到255之间。因此,我认为我的问题不在于有符号或无符号像素值。 - fdas
1
甚至更好的是,直接打印整个Mat:cout << img << endl;。而不仅仅是cout << int(uchar_value); - berak
2
这与有符号或无符号无关。任何类型的 char 默认情况下都会被打印为单个字符而不是数字。将其提升为更大的类型可以避免这种情况。(如果 cout << 'A' 打印 65,那么会引起混淆。归咎于向后兼容性。) - Alan Stokes
1
谢谢@berak,我通过你的回答解决了我的问题。谢谢。cout << int(image.at<Vec3b>(i,j)[0]) - fdas
显示剩余3条评论
4个回答

5
将每个输出转换为整数。
<< image.at<Vec3b>(i,j)[0] ...

变成

<< (int)image.at<Vec3b>(i,j)[0] ...

你正在打印一个 char(或可能是 unsigned char),它会作为单个字符通过流进行打印(在 255 时看起来像你所看到的)。将其转换为 int 强制显示值的数值表示。
其他答案改变了 image.at<type> 的方式,这会改变原始数据的解释方式;不要这样做。必须正确解释它们。

0

Vec3b px = image.at(x, y);

cout << "value: ("<<(int)px.val[0]<<", "<<(int)px.val[1]<<", "<<(int)px.val[2]<<")" << endl;

这对我有效。


0

image.at<Vec3b>(i, j)

改为

image.at<int>(i, j)

或者

image.at<double>(i, j)

或者

image.at<float>(i, j)

以打印值而不是字符


-2

您正在显示字符,请尝试使用函数 image.at<int>(j,i); 进行转换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接