在OpenCV 2.x中具有像素访问的错误 [英] Bug with pixel access in OpenCV 2.x
问题描述
我在尝试找到如何在新版本(2.x)的OpenCV中访问rgb像素时遇到问题。
这是我的代码
#include< opencv2\imgproc\imgproc.hpp>
#include< opencv2\highgui\highgui.hpp>
using namespace cv;
using namespace std;
int main(int argc,char * argv [])
{
Mat img;
string winMain =Main;
img = imread(argv [1]);
for(int j = 0; j {
for(int i = 0; i {
img.data [j * img.cols + i * 3 + 0] =(uchar)0; // B
//img.data [j * img.cols + i + 1] =(uchar)0; // G
//img.data [j * img.cols + i + 2] =(uchar)0; // R
}
}
namedWindow(winMain);
imshow(winMain,img);
waitKey();
return 1;
}
正如你可以注意到在下面的例子中,修改。
):
使用OP的代码生成的结果:
结果使用修改后的代码( j * img。 cols * 3
):
I'm having trouble trying to find out how to access rgb pixel in the new version (2.x) of OpenCV. I tried using a mix of the old and the new method but without success.
Here is my code
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\highgui\highgui.hpp>
using namespace cv;
using namespace std;
int main (int argc, char* argv[])
{
Mat img;
string winMain = "Main";
img = imread(argv[1]);
for (int j = 0; j < img.rows; j++)
{
for (int i = 0; i < img.cols; i++)
{
img.data[j * img.cols + i * 3 + 0] = (uchar)0; //B
//img.data[j * img.cols + i + 1] = (uchar)0; //G
//img.data[j * img.cols + i + 2] = (uchar)0; //R
}
}
namedWindow(winMain);
imshow(winMain, img);
waitKey();
return 1;
}
As you can notice in the following example, only a third of the image is modified.
Thanks for helping
I tested out your code, and I found the bug. You multiplied the column index by 3 (i * 3
), but it's also necessary to multiply the row index by 3 (j * img.cols * 3
).
I replaced j * img.cols
with j * img.cols * 3
:
for (int j = 0; j < img.rows; j++)
{
for (int i = 0; i < img.cols; i++)
{
img.data[j * img.cols * 3 + i*3 + 0] = (uchar)0; //B
//img.data[j * img.cols * 3 + i*3 + 1] = (uchar)0; //G
//img.data[j * img.cols * 3 + i*3 + 2] = (uchar)0; //R
}
}
Let's try an example.
Example image (from MIT pedestrian dataset):
Result using OP's code:
Result using the revised code (with j * img.cols * 3
):
这篇关于在OpenCV 2.x中具有像素访问的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!