[英]Difference in accessing pixel by at and by data OpenCV
今天,我觀察到一件有趣的事情:如果我使用函數“ at”訪問圖像像素,則會收到不同的結果,如果我使用圖像成員“數據”訪問圖像像素,則會收到不同的結果。
有人知道為什么會這樣嗎?
int main()
{
double sigma = 1.0;
cv::Mat verticalGaussianKernel = getGaussianKernel(7, sigma);
printImg(verticalGaussianKernel);
return 0;
}
void printImg(cv::Mat &img)
{
cout << "---------//------\n";
if (img.empty())
{
cout << "Empty Image\n";
return;
}
for (int i = 0; i < img.size().height; i++)
{
for (int j = 0; j < img.size().width; j++)
{
cout << int(img.data[i * img.size().height + j]) << " " << img.at<double>(i, j) << endl;
}
cout << endl;
}
cout << "---------//------\n";
}
它的代碼給出結果:
數據-------在
48 ------ 0.00443305
63 ------ 0.0540056
171 ----- 0.242036
251 ----- 0.39905
10 ------ 0.242036
12 ------ 0.0540056
84 ------ 0.00443305
首先,我認為數據中的值歸一化為0-255,但是最后一個字符串反駁了我的猜測
您的演員選錯了。 .data成員是一個uchar *,您要取消引用它,並將該值(單個uchar)轉換為int,這就是為什么未獲得正確值的原因。
正確的方法是將其轉換為double *,然后取消引用。 下面的代碼可以做到這一點。
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void printImg(cv::Mat &img) {
cout << "---------//------\n";
if (img.empty()) {
cout << "Empty Image\n";
return;
}
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
cout << reinterpret_cast<double *>(img.data)[i * img.cols + j]
<< " " << img.at<double>(i, j) << endl;
}
cout << endl;
}
cout << "---------//------\n";
}
int main() {
double sigma = 1.0;
cv::Mat verticalGaussianKernel = getGaussianKernel(7, sigma);
cout << verticalGaussianKernel << endl;
printImg(verticalGaussianKernel);
return 0;
}
輸出:
[0.004433048175243745;
0.05400558262241448;
0.2420362293761143;
0.3990502796524549;
0.2420362293761143;
0.05400558262241448;
0.004433048175243745]
---------//------
0.00443305 0.00443305
0.0540056 0.0540056
0.242036 0.242036
0.39905 0.39905
0.242036 0.242036
0.0540056 0.0540056
0.00443305 0.00443305
您正在以char形式讀取數據。 而是將其作為雙讀
int main()
{
double sigma = 1.0;
cv::Mat verticalGaussianKernel = getGaussianKernel(7, sigma);
printImg(verticalGaussianKernel);
return 0;
}
void printImg(cv::Mat &img)
{
cout << "---------//------\n";
if (img.empty())
{
cout << "Empty Image\n";
return;
}
for (int i = 0; i < img.size().height; i++)
{
for (int j = 0; j < img.size().width; j++)
{
cout << double(img.data[i * img.size().height*sizeof(double) + j*sizeof(double)]) << " " << img.at<double>(i, j) << endl;
}
cout << endl;
}
cout << "---------//------\n";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.